使用Composite键的聚合函数

时间:2016-01-18 09:56:04

标签: sql sql-server sql-server-2008 sql-server-2008-r2

SELECT CollMstHdr.EntryNo, CollMstHdr.Date, PartyMst.PName, SUM(CollMstDtl.Amt)
FROM CollMstHdr
  INNER JOIN CollMstDtl ON CollMstHdr.EntryNo = CollMstDtl.EntryNo
  INNER JOIN PartyMst ON CollMstHdr.SPartyCd = PartyMst.PartyCd
group by CollMstHdr.EntryNo, CollMstHdr.Date, PartyMst.PName

根据CollMstHdr.EntryNo和CollMstHdr.Date,我想要Amt Amt,我有EntryNo和Date两个主键,但仅根据EntryNo得到Amt Sum。 如何使用Group By Clouse当我们有两列作为主要的kays时。

1 个答案:

答案 0 :(得分:0)

首先按照表格结构执行连接。 然后将列添加到要执行分组的 select和group by 子句中。

就像你想要在EntryNo和Date上进行分组一样,然后执行以下操作:

SELECT CollMstHdr.EntryNo, CollMstHdr.Date, SUM(CollMstDtl.Amt)
FROM CollMstHdr
  INNER JOIN CollMstDtl ON CollMstHdr.EntryNo = CollMstDtl.EntryNo
  INNER JOIN PartyMst ON CollMstHdr.SPartyCd = PartyMst.PartyCd
group by CollMstHdr.EntryNo, CollMstHdr.Date

如果您只想在EntryNo上进行分组,请执行以下操作:

SELECT CollMstHdr.EntryNo, SUM(CollMstDtl.Amt)
FROM CollMstHdr
  INNER JOIN CollMstDtl ON CollMstHdr.EntryNo = CollMstDtl.EntryNo
  INNER JOIN PartyMst ON CollMstHdr.SPartyCd = PartyMst.PartyCd
group by CollMstHdr.EntryNo