2013-01-17 45 views
-1

我有列名的表:SQL各種組合由

類別1,類別2,類別3,價值

我想從表如下組合:

---> category1,count(*) 

---> category1, category2, count(*) 

---> category2, category3, count(*) 

是有一種方法可以在一個查詢中執行此操作,還是我真的需要編寫3個單獨的查詢?我想設計的類似以下內容:

Category1, Category2, Category3, CountNumber 

凡的情況1,類別2和類別3欄是空白,對於情況2 3類別欄將是空白的,等

--------EXAMPLE--------------------------------------------------------- 
Cat1   Cat2   Cat3  Value 
a    NULL   d1   13 
b    e1    d1   13 
a    e2    d1   13 
c    NULL   d2   13 
a    e1    d1   13 
a    NULL   d1   13 
--------DESIRED OUTPUT ------------------------------------------------- 
Cat1   Cat2   Cat3   CountNumber 
a    NULL   NULL   4 
b    NULL   NULL   1 
c    NULL   NULL   1 
a    e1    NULL   1 
c    e1    NULL   0 
NULL   e1    d1    2 

等在 感謝

+1

您使用的是什麼rdbms? – Taryn

+0

sybase ..不知道這是否算作RDBMS – Zanam

回答

1

試試這個

Select category1, null Category2, null category3, count(*) 
from table 
group by category1 
UNION ALL 
Select category1, category2, null category3, count(*) 
from table 
group by category1, category2 
UNION ALL 
Select null category1,category2, category3, count(*) 
from table 
group by category2, category3 

中插入行在tmp表中

SELECT * INTO TmpTable FROM (
Select category1, null Category2, null category3, count(*) 
from table 
group by category1 
UNION ALL 
Select category1, category2, null category3, count(*) 
from table 
group by category1, category2 
UNION ALL 
Select null category1,category2, category3, count(*) 
from table 
group by category2, category3) x 
+0

如何將上述內容插入臨時表中?是否有可能進行上面的計算並將它們一步插入臨時表中? – Zanam

+0

@ user1949158檢查更新answe –

+0

非常感謝您的快速回復。 – Zanam