SQL SUM相同的列

时间:2016-10-04 20:35:17

标签: sql sql-server

我有一张桌子

CREATE TABLE [dbo].[StackOverflow]
(
    [ArticleId] [bigint] NULL,
    [Quantity] [decimal](18, 0) NULL,
    [Type] [smallint] NULL
) ON [PRIMARY]

在此表中,我有一些看起来像这样的结果

ArticleId     Quantity     Type
------------- ------------ ------
10               50          1
12               20          1
10               10          1
10               18          1
12                5          2
17               14          2
10               30          2
  • 类型1表示该文章计划用于生产
  • 类型2表示文章已完成

我需要输出查询,显示所有文章的列表

输出=已完成 - 已完成

示例:ArticleId:10计划数量为:78已完成数量为:

30输出= 78 - 30 = 48

我真的没有什么可展示的。我只知道我需要按ArticleId进行分组。

我试过这个

SELECT
    articleid,
    SUM(quantity) - (SELECT SUM(quantity)
                     FROM stackoverflow
                     WHERE type = 2
                       AND main.articleId = stackoverflow.articleId
                     GROUP BY articleid)
FROM 
    stackoverflow AS main
WHERE 
    type = 1
GROUP BY 
    articleid

2 个答案:

答案 0 :(得分:9)

你可以使用案例和总和

select ArticleId , sum( case type 
                       when 1 then Quantity
                       when 2 then -Quantity
                     end) Output 
from stackoverflow  
group by ArticleId

答案 1 :(得分:3)

您需要减去两种类型的汇总总和:

SELECT
  [ArticleId],
  SUM(CASE WHEN [Type] = 1 THEN [Quantity] ELSE 0 END) - SUM(CASE WHEN [Type] = 2 THEN [Quantity] ELSE 0 END) AS [PlannedSubQuantityTotal]
FROM [dbo].[StackOverflow]
GROUP BY [ArticleId]

或使用"技巧"总结与计划完成并使用-前缀:

SELECT
  [ArticleId],
  SUM(CASE WHEN [Type] = 1 THEN [Quantity] WHEN [Type] = 2 THEN -[Quantity] ELSE 0 END) AS [PlannedSubQuantityTotal]
FROM [dbo].[StackOverflow]
GROUP BY [ArticleId]