SQL的各种组合用于分组

时间:2013-01-17 18:24:32

标签: sql sybase

我有一个包含列名的表:

category1,category2,category3,Value

我想从表中获得以下组合:

---> 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 个答案:

答案 0 :(得分: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