开发者

pivoting for two columns

开发者 https://www.devze.com 2023-01-12 22:22 出处:网络
HI, Using SQL server 2005 I have the following query: SELECT contact_id ,YEAR(date_created)AS giftyear ,SUM(amount_exc_vat)AS year_total_xGA

HI, Using SQL server 2005 I have the following query:

SELECT 
contact_id      
,YEAR(date_created)         AS giftyear
,SUM(amount_exc_vat)        AS year_total_xGA
,SUM(amount_inc_vat)        AS year_total_inGA
,COUNT(*) AS numGifts 
FROM gifts 
GROUP BY contact_id 
,Year(date_created)

Which returns data that looks like this:

contact_id  |  giftyear  | year_total_xVAT  |year_total_inVAT  |  numGifts
id001      |    2006    |   17.00          |      21.79       |     4
id001      |    2007    |   5.00           |    6.41          |     1
id001       |   2008    |   5.00           |       6.41       |     1

I then want to pivot this data to have the table looking like this instead

contact_id  |  gift_2006  |  2006_excVAT  | 2006_incVAT  | 2007gifts | 2007_excVAT  |  2007_incVAT | gift_2008  |  2008_excvat  |  2008_incvat
id001       |  开发者_StackOverflow中文版  1        |     17.00     |    21.79     |  1        |    5.00      |  6.41         |    1       |    5.00       |    6.41

So where gift_2006 etc is essentially a CASE statement saying if the contact_id gave a gift in 2006 then assign 1 else 0 - so that for one contact all of the information is contained in one row

Thanks in advance :)


SELECT 
contact_id,   
 CASE WHEN COUNT(CASE WHEN YEAR(date_created) = 2006 THEN 1 END) > 0 THEN 1 ELSE 0 END AS gift_2006,
SUM(CASE WHEN YEAR(date_created) = 2006 THEN amount_exc_vat END) AS [2006_excVAT] ,
SUM(CASE WHEN YEAR(date_created) = 2006 THEN amount_inc_vat END) AS [2006_incVAT] ,
CASE WHEN COUNT(CASE WHEN YEAR(date_created) = 2007 THEN 1 END) > 0 THEN 1 ELSE 0 END AS gift_2007,
SUM(CASE WHEN YEAR(date_created) = 2007 THEN amount_exc_vat END) AS [2007_excVAT] ,
SUM(CASE WHEN YEAR(date_created) = 2007 THEN amount_inc_vat END) AS [2007_incVAT] ,
CASE WHEN COUNT(CASE WHEN YEAR(date_created) = 2008 THEN 1 END) > 0 THEN 1 ELSE 0 END AS gift_2008,
SUM(CASE WHEN YEAR(date_created) = 2008 THEN amount_exc_vat END) AS [2008_excVAT] ,
SUM(CASE WHEN YEAR(date_created) = 2008 THEN amount_inc_vat END) AS [2008_incVAT] 
FROM gifts 
GROUP BY contact_id 
0

精彩评论

暂无评论...
验证码 换一张
取 消