2015-11-06 56 views
0

我有一個巨大的SQL,其結果與Table1相似。現在我需要將結果集作爲Table2。這是來自SQL Server的,但我們沒有將數據庫訪問作爲典型的方式,相反,我們有一個內部工具,我們可以在其中提交'select'SQL語句,並將數據集轉儲爲excel文件。我怎樣才能得到結果爲table2格式?SQL:如何獲取聚合列值並填充爲新列

注:由於該工具的性質,我們只能使用SQL命令,不能創建StoredProcedure時,查看等

我們可以做這樣的事?

SELECT 'Columns' From (Original SQL command) WHERE xxx GROUPBY YYY 

表1

IDNameKey  |ID  |Name |Location  |Type |Active 
================|=======|=======|===============|=======|===== 
111    |11  |AAA |LocA   |Type1 |No 
222    |22  |BBB |LocB   |Type2 |Yes 
333    |33  |CCC |LocA   |Type4 |No 
444    |11  |AAA |LocC   |Type2 |Yes 
555    |55  |EEE |LocB   |Type4 |No 
666    |22  |BBB |LocB   |Type2 |Yes 

表2(預期方式)

ID  |Name |Location |Type |Active Count(Yes) |Inactive Count(No) 
========|=======|=========|=======|===================|================= 
11  |AAA |LocA  |Type1 |1     |1 
22  |BBB |LocB  |Type2 |2     |0 
33  |CCC |LocA  |Type4 |0     |1 
55  |EEE |LocB  |Type4 |0     |1 

回答

1

使用條件的總和

SELECT ID, Name, Location, Type, 
      SUM(CASE WHEN Active = 'Yes' THEN 1 ELSE 0 END) as [Active Count(Yes)], 
      SUM(CASE WHEN Active = 'No' THEN 1 ELSE 0 END) as [Active Count(No)] 

    From (Original SQL command) 
    GROUP BY ID, Name, Location, Type 
+0

謝謝你,它的工作。 – Vins007

0

對於初學者來說,給這個一掄..

SELECT ID, Nave, Location, Type, 
    SUM(CASE Active WHEN 'Yes' THEN 1 WHEN 'No' THEN 0 END) as [Active Count(Yes)], 
    SUM(CASE Active WHEN 'No' THEN 1 WHEN 'Yes' THEN 0 END) as [Inactive Count(No)] 
FROM Table1 
GROUP BY ID, Nave, Location, Type 

有關CASE塊的編碼和圖像重教程參考我的文章SQL Server CASE Solutions