获取明细表的总和

of1yzvn4  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(280)

我需要检索一个主记录及其详细信息的总和。以下是两个表的定义:
主表(master)

ID
Name

示例记录:

10 Product

明细表(details)

master_id
type (values can only be red or blue)
quantity

示例记录:

10 red 2
10 red 5
10 red 6
10 blue 7
10 blue 9

我需要这样的结果:

10 Product 13 (sum for red) 16 (sum for blue)

数据库是sql server 2017。如果不使用存储过程,如何编写单个查询?
---更新---
根据venkataraman r的输入,以下是解决方案:

SELECT m.id, m.name ,
SUM(CASE when type='red' then quantity end) as redsum,
SUM(CASE when type='blue' then quantity end) as bluesum
from mydetails as t
inner join mymaster as m
on m.id = t.master_id
GROUP BY m.id, m.name
gojuced7

gojuced71#

您可以将concat函数与groupby一起使用,以获得单个语句的结果。

DECLARE @table table(master_id int, typev varchar(10), quantity int)
DECLARE @master table(id int, name varchar(50))

insert into @master values(10, 'Product10')

insert into @table values
(10,'red',  2),
(10,'red',  5),
(10,'red',  6),
(10,'blue', 7),
(10,'blue', 9);

SELECT m.name ,
SUM(CASE when typev='red' then quantity end) as redsum,
SUM(CASE when typev='blue' then quantity end) as bluesum
from @table as t
inner join @master as m
on m.id = t.master_id
GROUP BY m.name
+-----------+--------+---------+
|   name    | redsum | bluesum |
+-----------+--------+---------+
| Product10 |     13 |      16 |
+-----------+--------+---------+
lb3vh1jj

lb3vh1jj2#

如果我得到你正确的话,那么你正在寻找枢轴,在这种情况下,你可以使用 case 表达式如下

select
    master_id,
    sum(case when type = 'red' then quantity end) as sum_of_red,
    sum(case when type = 'blue' then quantity end) as sum_of_blue
from yourTable
group by
    master_id

如果您只是想按类型列出总数量,那么请使用以下命令

select
    master_id,
    type,
    sum(quantity) as total_quantity
from yourTable
group by
    master_id,
    type
cvxl0en2

cvxl0en23#

就用一个小组

Select master_id, type, sum(quantity)
    From details group by master_id, type

并使用pivot在一行中显示每个产品

With data_cte as 
    (Select master_id, type, sum(quantity)
    From details group by master_id, type)

    Select * from data_cte pivot (
    For type in ('red', 'black'))

相关问题