转动两列

时间:2010-08-20 10:44:06

标签: sql sql-server-2005

HI, 使用SQL Server 2005我有以下查询:

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)

返回如下所示的数据:

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

然后我想转动这些数据,使表格看起来像这样

contact_id  |  gift_2006  |  2006_excVAT  | 2006_incVAT  | 2007gifts | 2007_excVAT  |  2007_incVAT | gift_2008  |  2008_excvat  |  2008_incvat
id001       |    1        |     17.00     |    21.79     |  1        |    5.00      |  6.41         |    1       |    5.00       |    6.41

所以,gift_2006等本质上是一个CASE声明,说明contact_id是否在2006年赠送了礼物,然后分配1其他0 - 所以对于一个联系人,所有信息都包含在一行中

提前致谢:)

1 个答案:

答案 0 :(得分:2)

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