我想创建3组以上的人,但我的问题是有些项目属于多个组(有各种子组)。当使用case语句时我无法重现这些结果,因为它第一次看到结果时会被计算,然后在下一个if语句中被忽略。
Select Column1, Column2,
CASE
WHEN(number IN (1,2,3,4,5,6,7,8)) then 'Group1'
WHEN(number IN (1,2,3,4)) then 'Group2'
WHEN(number IN (9,10,11,12)) then 'Group3'
ELSE 'Group4' END
AS Categories,
SUM(Gross_Sales)
第1组将拥有我想要的一切,第2组是空的(正如预期时使用的情况一样),然后第3组将拥有我想要的一切。我怎么会重写这个?
假设我的表包含以下数据:
| Number | Gross_Sales |
|---------------------|------------------|
| 1 | 10 |
|---------------------|------------------|
| 2 | 10 |
|---------------------|------------------|
| 8 | 10 |
|---------------------|------------------|
我希望输出显示为:
组1:30
第2组:20
Group3:0
目前返回:
组1:30
第2组:0
Group3:0
答案 0 :(得分:1)
你可以试试这个 -
Select Field1, Field2,
CASE
WHEN(number IN (1,2,3,4)) then 'Group1 & Group 2'
WHEN(number IN (5,6,7,8)) then 'Group1'
WHEN(number IN (9,10,11,12)) then 'Group3'
ELSE 'Group4' END
AS Categories
答案 1 :(得分:0)
我认为UNION将是解决这个问题的最好方法:
Select Column1, Column2,
CASE WHEN(number IN (1,2,3,4,5,6,7,8)) then 'Group1' as categories
FROM ...
UNION ALL
Select Column1, Column2,
CASE WHEN(number IN (1,2,3,4)) then 'Group2' as categories
FROM ...
UNION ALL
Select Column1, Column2,
CASE WHEN(number IN (9,10,11,12)) then 'Group3' as categories
FROM ...
UNION ALL
Select Column1, Column2,
CASE WHEN(number NOT BETWEEN 1 AND 12) then 'Group4' as categories
FROM ...
您可能希望在子查询中运行此逻辑,然后加入结果,而不是在联合中反复执行您的大喇叭sql。
答案 2 :(得分:0)
我不确定您的结果集是否必须在行中,但如果您可以在一行中处理结果,则可以这样做:
SELECT
SUM(CASE WHEN Number BETWEEN 1 AND 8 THEN Gross_Sales ELSE 0) AS Group1,
SUM(CASE WHEN Number BETWEEN 1 AND 4 THEN Gross_Sales ELSE 0) AS Group2,
SUM(CASE WHEN Number BETWEEN 9 AND 12 THEN Gross_Sales ELSE 0) AS Group3,
SUM(CASE WHEN Number NOT BETWEEN 1 AND 12 THEN Gross_Sales ELSE 0) AS Group4
FROM MyTable
如果您需要将其作为样本输出中的行返回,则可以使用pivot函数或公用表表达式+联合。