0

我正在创建一个有奇怪情况的报告:

我有一张如下表:

原因

原因ID 原因名称
1 烧伤
2 焊接烧伤
3 点烧

容器

容器 原因名称 缺陷数量
一个 烧伤 4
一个 焊接烧伤 10
点烧 15

我想要做的是将所有 3 个值组合为 1 以便当我运行查询时

Select container, defectqty 
from container 
where reasonname = 'burn' and container = 'A'

我的输出如下所示:

容器 缺陷数量
一个 14

我以为我会使用案例条件,但我有点迷路了

4

2 回答 2

0
select container,case
when container='A' Then sum(Defectqty)
when container='B' Then sum(Defectqty)
end as Defectqty
from container group by container
于 2021-06-22T04:51:38.583 回答
0

您可以使用派生表尝试以下 sql 查询。你不需要加入。您想要的一切都在单个表中可用:容器。

declare @table table(container char(1), reasonName varchar(30), defectqty int)

insert into @table values
('A','Burn',    4),
('A','Weld Burn',   10),
('B','Spot Burn',   15)

SELECT container, reasonName, total_defectqty from
(select *, sum(defectqty) over (partition by container) as total_defectqty from @table) as t
WHERE ReasonName = 'Burn' and container = 'A'
容器 原因名称 total_defectqty
一个 烧伤 14
于 2021-06-22T10:58:20.150 回答