我有一个包含两列的数据集。我想将其中一列分类为bin,然后将每个bin中另一列中的值求和。
我尝试了以下代码
select DISTINCT (
CASE WHEN H=1 THEN '1'
WHEN H BETWEEN 2 AND 3 THEN '2-3'
WHEN H BETWEEN 4 AND 6 THEN '4-6'
ELSE '' END
) AS H , sum(V) [V]
from
TABLE1 inner join TABLE 2 on TABLE1.X=TABLE2.X
where
TABLE.X=1 and Y='id'
GROUP BY H
ORDER BY H ASC
下表提供了我的数据示例(其中H和V为标题)
H V
1 100
1 1000
1 1500
2 300
3 500
4 9000
5 800
6 1100
我想要的输出是
H V
1 2600
2 TO 3 800
4 TO 6 10900
但是,我正在获取(即重复的bin,因为未将V列的值合并到每个bin中的所有值中)
H V
1 100
1 1000
1 1500
2-3 300
2-3 500
4-6 9000
4-6 800
4-6 1100
答案 0 :(得分:0)
您似乎想要聚合计算列:
select (CASE WHEN H = 1 THEN '1'
WHEN H BETWEEN 2 AND 3 THEN '2-3'
WHEN H BETWEEN 4 AND 6 THEN '4-6'
ELSE ''
END) AS H , sum(V) as V
from TABLE1 inner join
TABLE2
on TABLE1.X = TABLE2.X
where TABLE.X = 1 and Y = 'id'
GROUP BY (CASE WHEN H = 1 THEN '1'
WHEN H BETWEEN 2 AND 3 THEN '2-3'
WHEN H BETWEEN 4 AND 6 THEN '4-6'
ELSE ''
END)
ORDER BY MIN(H) ASC;
您应该限定查询中的所有列引用。
SELECT DISTINCT
几乎永远不适用于GROUP BY
。