格式化语句时的SUM大小写时的正确语法

时间:2016-11-30 00:32:22

标签: sql-server sum case-when

我想在我的数据库中总结两个不同的值。

Species可以是12或14.我已经在select语句中删除了其余部分。

我希望对物种值为12的所有行执行总计SUM,并在物种值为14时执行相同的操作。

我不明白如何格式化语法。这是我的问题:

SELECT h.HarvestDate, c.LotNo, h.Producer, c.species
    SUM CASE WHEN c.Species = 12 THEN LambYT ELSE 0 as LambYT
    SUM CASE WHEN c.Species = 14 THEN LambYTSpoolJoint ELSE 0 as LambYTSpoolJoint
FROM BANSS.dbo.DixonCarcass_InProcess c, BANSS.dbo.HarvestData_SFDCApp h
WHERE c.LotNo = h.Lot
    AND c.Species in (12, 14)
    AND h.Program not LIKE 'K&R%'
GROUP BY h.HarvestDate, c.LotNo, h.Producer

但我认为这是不正确的。我想要一个SUM Species = 12和一个Species = 14的总和,以及两个总和TOTAL

2 个答案:

答案 0 :(得分:0)

我不清楚你想要什么,但试试这个:

SELECT 
    h.HarvestDate, 
    c.LotNo, 
    h.Producer, 
    c.species,
    SUM(LambYT) AS LambYT,
    SUM(LambYTSpoolJoint) AS LambYTSpoolJoint
FROM 
    BANSS.dbo.DixonCarcass_InProcess c, 
    BANSS.dbo.HarvestData_SFDCApp h
WHERE 
    c.LotNo = h.Lot
    AND c.Species IN (12, 14)
    AND h.Program NOT LIKE 'K&R%'   
GROUP BY 
    h.HarvestDate, 
    c.LotNo, 
    h.Producer,
    c.species

或者,如Tim B.建议的那样,试试:

SELECT 
    h.HarvestDate, 
    c.LotNo, 
    h.Producer, 
    c.species,
    SUM(CASE WHEN c.Species = 12 THEN LambYT ELSE 0 END) AS LambYT,
    SUM(CASE WHEN c.species = 14 THEN LambYTSpoolJoint ELSE 0 END) AS LambYTSpoolJoint
FROM 
    BANSS.dbo.DixonCarcass_InProcess c, 
    BANSS.dbo.HarvestData_SFDCApp h
WHERE 
    c.LotNo = h.Lot
    AND c.Species IN (12, 14)
    AND h.Program NOT LIKE 'K&R%'   
GROUP BY 
    h.HarvestDate, 
    c.LotNo, 
    h.Producer,
    c.species

或者,更好的是,

SELECT 
    h.HarvestDate, 
    c.LotNo, 
    h.Producer, 
    c.species,
    CASE WHEN c.Species = 12 THEN SUM(LambYT) ELSE SUM(LambYTSpoolJoint) END AS LambYT
FROM 
    BANSS.dbo.DixonCarcass_InProcess c, 
    BANSS.dbo.HarvestData_SFDCApp h
WHERE 
    c.LotNo = h.Lot
    AND c.Species IN (12, 14)
    AND h.Program NOT LIKE 'K&R%'   
GROUP BY 
    h.HarvestDate, 
    c.LotNo, 
    h.Producer,
    c.species

答案 1 :(得分:0)

尝试此查询:

SELECT h.HarvestDate,
       c.LotNo,
       h.Producer,
      SUM(CASE WHEN c.Species = 12 THEN 1 ELSE 0 END) AS LambYT,
      SUM(CASE WHEN c.species = 14 THEN 1 ELSE 0 END) AS LambYTSpoolJoint,
      SUM(CASE WHEN c.Species = 12 THEN 1 ELSE 0 END) +
      SUM(CASE WHEN c.species = 14 THEN 1 ELSE 0 END) AS TOTAL
FROM BANSS.dbo.DixonCarcass_InProcess c
INNER JOIN BANSS.dbo.HarvestData_SFDCApp h
    ON c.LotNo = h.Lot
WHERE c.Species IN (12, 14) AND
      h.Program NOT LIKE 'K&R%'
GROUP BY h.HarvestDate, c.LotNo, h.Producer

备注:

没有办法进行单一聚合来获得总数,因为对于物种12和14,求和的列是不同的。所以,我只是将各自的CASE表达式加在一起。

您无法选择c.species,因为它未显示在您的SELECT列表中,并且不在聚合函数中。

我将隐式连接替换为显式连接,其中连接条件出现在ON子句中。这是现在接受的标准,它使您更容易阅读查询。