对于SELECT作业列表(包括sme特定详细类型的SUM()),我需要一个SQL查询。
我有一个包含运输数据的数据库。表格看起来像这样:
job:
idjob | customer
1 | 45
2 | 38
3 | 15
job-detail:
iddet | idjob | type | value
1 | 1 | range | 100
2 | 1 | range | 85
3 | 1 | range | 12
4 | 1 | price | 64
4 | 1 | price | 5
5 | 1 | note | Some text here
6 | 2 | range | 150
7 | 2 | price | 32
8 | 2 | note | Some text here
9 | 2 | range | 35
我需要以下输出:
idjob | customer | total_range | total_price
1 | 45 | 197 | 69
2 | 38 | 185 | 32
3 | 15 | 0 | 0
答案 0 :(得分:3)
您可以将左联接与条件聚合一起使用
select a.idjob,customer,
sum(case when type='range' then value end) as total_range,
sum(case when type='price' then value end) as total_price
from job a
left join job-detail b on a.idjob=b.idjob
group by a.idjob,customer
答案 1 :(得分:0)
SELECT DISTINCT J.idjob, J.customer,
(SELECT SUM(CONVERT(INT, [VALUE])) FROM [dbo].[job-detail] WHERE TYPE = 'range' AND J.idjob = idjob) AS total_range,
(SELECT SUM(CONVERT(INT, [VALUE])) FROM [dbo].[job-detail] WHERE TYPE = 'price' AND J.idjob = idjob) AS total_price
FROM [dbo].[job] j
LEFT JOIN [dbo].[job-detail] JD ON J.idjob = JD.idjob