对具有相同标识号的行求和并按自定义顺序排序

时间:2018-11-06 10:00:19

标签: sql sql-server group-by

我对“产品”表具有以下表结构:

id    amount    number
1     10        M6545
2     32        M6424
3     32        M6545
4     49        M6412
...   ...       ...

我想选择所有具有相同编号的行的总和。具有相同编号的行应加起来为一个总和。这意味着:

  

M6545->总和42

     

M6424->总和32

     

M6421->总和49

我的查询如下所示,但仍然无法正常工作:

SELECT SUM(amount) as SumAm FROM products WHERE number IN ('M6412', 'M6545')

我想找到一种方法,我只能选择“ IN”语句中数字顺序的和。这意味着结果表应如下所示:

SumAm
49
42

总和不应以某种方式排序。它应该与IN子句中的数字顺序匹配。

4 个答案:

答案 0 :(得分:3)

使用 import 'rxjs/add/operator/map';

group by

但是,如果只想使用“ M6412”,“ M6545”,则需要在第二个输出样本中显示的where子句

答案 1 :(得分:2)

使用分组依据和汇总

SELECT SUM(amount) as SumAm FROM products
WHERE number IN ('M6412', 'M6545') 
group by number

答案 2 :(得分:1)

您的要求是无稽之谈... IN的工作方式并非如此。话虽如此,以下内容将以所需的顺序为您提供结果:

SELECT SUM(amount)
FROM (VALUES
    ('M6545', 1),
    ('M6412', 2)
) AS va(number, sortorder)
INNER JOIN sumam ON va.number = sumam.number
GROUP BY va.number, va.sortorder
ORDER BY va.sortorder

当您需要为每个数字添加WHEN条件时,这比编写CASE语句要好一些。

答案 3 :(得分:1)

您不能直接根据IN子句的顺序对结果进行排序。
您可以执行以下操作:

SELECT SUM(amount) as SumAm 
FROM products 
WHERE number IN ('M6412', 'M6545')
GROUP BY number -- You must group by to get a row for each number
ORDER BY CASE number 
             WHEN 'M6412' THEN 1
             WHEN 'M6545' THEN 2
         END

当然,您在IN子句中拥有的项目越多,此查询将变得越麻烦。因此,另一种解决方案可能更实用-联接到表变量而不是使用IN

DECLARE @Numbers AS TABLE 
(
    sort int identity(1,1), -- this will hold the order of the inserted values 
    number varchar(10) PRIMARY KEY -- enforce unique values
);

INSERT INTO @Numbers (number) VALUES
('M6412'), 
('M6545')

SELECT SUM(amount) as SumAm 
FROM products As p
JOIN numbers As n ON p.Number = n.Number
-- number and sort have a 1 - 1 relationship, 
-- so it's safe to group by it instead of by number
GROUP BY n.sort 
ORDER BY n.sort