-1

我有一个包含列名的表:

类别 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

等等谢谢

4

1 回答 1

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
于 2013-01-17T18:50:26.307 回答