[英]How can I group rows in SQL and sum them up?
假设我在 SQL Server 2017 中有这样的表,我们称之为“maps_and_cups”
一些代码 | 数量 |
---|---|
大地图 | 6 |
tiny_map | 5 |
大杯 | 10 |
小杯 | 4 |
我想知道以这种方式将地图和杯子组合为一个的最佳方法。
一些代码 | 数量 |
---|---|
地图 | 11 |
杯子 | 14 |
我知道它使用“if”和“case”,添加和比较它是否是 tiny_map、big_map 等等,我看过几个例子,但我无法编译。
您确实可以使用case when
表达。 例如:
with base as
(select case some_code when 'big_map' then 'maps'
when 'tiny_map' then 'maps'
when 'big_cup' then 'cups'
when 'tiny_cup' then 'cups'
else 'other'
end grp,
quantity
from maps_and_cups)
select grp, sum(quantity) quantity from base group by grp;
但是,如果您要明确列出每个代码,则不妨为其创建一个参考表:
一些代码 | grp |
---|---|
大地图 | 地图 |
tiny_map | 地图 |
大杯 | 杯子 |
小杯 | 杯子 |
...然后将该表加入您的查询中:
select grp, sum(quantity)
from maps_and_cups a left join ref_maps_cups b on a.some_code = b.some_code
group by grp;
您可以使用“case”和“charindex”函数来解决此任务,如下所示:
declare
@t table (some_code varchar (20), quantity int)
insert into @t
values
('big_map', 6),
('tiny_map', 5),
('big_cup',10),
('tiny_cup', 4)
select
case
when charindex ('map', some_code)>0 then 'map'
when charindex ('cup', some_code)>0 then 'cup'
end some_code
,sum(quantity) quantity
from @t
group by
case
when charindex ('map', some_code)>0 then 'map'
when charindex ('cup', some_code)>0 then 'cup'
end
如果您只想要正确的三个字符进行聚合,您可以使用right()
:
select right(some_code, 3) + 's', sum(quantity)
from maps_and_cups
group by right(some_code, 3) + 's';
您正在为自己制造一个问题,因为您(可能)通过在“some_code”字段中存储非原子值来打破第一个正常形式。 (我会说一些字段名称。;)
为什么不将值分成 [type] 和 [size]?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.