SQL选择总和查询

时间:2011-11-11 12:30:42

标签: sql types group-by sum case

我需要完成以下内容,但需要在EntryValue上使用SUM,其中EntryType =' C' - EntryType =' D'但不知道在哪里包括它。

SELECT SUM(EntryValue) AS EntryValue, Left(Warehouse,1) AS Branch 
FROM GenJournalDetail INNER JOIN InvJournalCtl ON (GenJournalDetail.GlPeriod = InvJournalCtl.LedgPeriod) AND (GenJournalDetail.GlYear = InvJournalCtl.YearPostLedg) AND (GenJournalDetail.Journal = InvJournalCtl.GlJournal)
WHERE GenJournalDetail.GlCode = 'Z5207550' AND GlYear = '2011' AND GlPeriod = '10' 
GROUP BY Left(InvJournalCtl.Warehouse,1) 

2 个答案:

答案 0 :(得分:2)

选择它然后将其分组;

SELECT SUM(EntryValue) AS EntryValueTotal, EntryType, Left(Warehouse,1) AS Branch 
...
GROUP BY Left(InvJournalCtl.Warehouse,1), EntryType

编辑我没有意识到你想要扣除;

SELECT
    SUM(CASE EntryType
        WHEN 'C' THEN EntryValue
        ELSE 0 END
    )
    -
    SUM(CASE EntryType
        WHEN 'D' THEN EntryValue
        ELSE 0 END
    ) AS EntryValueTotal, 
    Left(Warehouse,1) AS Branch 
FROM GenJournalDetail 
  INNER JOIN InvJournalCtl ON (GenJournalDetail.GlPeriod = InvJournalCtl.LedgPeriod) AND (GenJournalDetail.GlYear = InvJournalCtl.YearPostLedg) AND (GenJournalDetail.Journal = InvJournalCtl.GlJournal)
WHERE 
  GenJournalDetail.GlCode = 'Z5207550' AND GlYear = '2011' AND GlPeriod = '10' 
GROUP BY Left(InvJournalCtl.Warehouse,1) 

答案 1 :(得分:0)

如果您需要对列进行求和,请将其添加到select和group中:

SELECT SUM(EntryValue) AS TotEntry, ...
...
GROUP BY ...

您不需要对聚合列进行分组;你还需要过滤查询吗?