Repeating data in union query

  • Hi. Very newbie....

    I have a query I've written. I've taken most of the dates and unions out but sample below. Next month I'll need to add in an additional line for Jan 10 for each select statement. Is there anyway I can set this once and get each query to look at it without creating a new table?

    select 'Jan08'

    , sum((case when c.closing_date >= '2009-11-01' and c.closing_date < '2009-12-01' then 1 else 0 end)) as Nov09

    , sum((case when c.closing_date >= '2009-12-01' and c.closing_date < '2010-01-01' then 1 else 0 end)) as Dec09

    from sales s left outer join closed c

    on s.sortcode = c.sort_code and s.accountnumber = c.acc_num

    where s.datesold >='2008-01-01' and s.datesold < '2008-02-01'

    union

    select 'Feb08'

    , sum((case when c.closing_date >= '2009-11-01' and c.closing_date < '2009-12-01' then 1 else 0 end)) as Nov09

    , sum((case when c.closing_date >= '2009-12-01' and c.closing_date < '2010-01-01' then 1 else 0 end)) as Dec09

    from Stock2008..salesrecord s left outer join ClosedAccounts..customers c

    on s.sortcode = c.sort_code and s.accountnumber = c.acc_num

    where s.datesold >='2008-02-01' and s.datesold < '2008-03-01'

    etc etc

  • Absolutely. See the following link. Almost exactly what you need...

    http://www.sqlservercentral.com/articles/Crosstab/65048/

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply