2010-08-20 59 views
1

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臺tement說如果CONTACT_ID了2006年的禮物然後分配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 
+0

感謝當我嘗試這個我得到的錯誤是說date_created不包含在聚合中,當我添加它時會爲每個contact_id產生重複的行。另外,我從一些人那裏聽說CASE語句是最有效的,所有這些嵌套的CASE語句會使事情減慢很多? - 謝謝, – Dibstar 2010-08-20 11:18:16

+0

@達文 - 那是最基本的想法。由於您沒有在您的文章中提供任何DDL(創建表語句),因此我沒有對此進行測試。如果你編輯你的問題,包括創建表格腳本的禮物,我會做的。這是做這件事唯一合理的方式。對於這種方法,「Pivot」操作符基本上是語法糖。 – 2010-08-20 11:21:13

+0

順便說一下,我只是測試它的結果,並沒有得到任何這樣的錯誤。你確定你沒有改變任何東西嗎? – 2010-08-20 11:28:34