如何在SQL中每个UniqueId只有一次SUM?

时间:2016-09-23 15:22:17

标签: sql sql-server sql-server-2005

我有两张看起来像这样的表:

表A

DocumentId (*is unique) DocumentDate
1                       2016-01-01
2                       2016-01-01
3                       2016-02-01
4                       2016-03-01

和表B

ContractId SnapshotTimeId NetFinanced
1          20160231       300
1          20160331       300
1          20160431       300
2          20160231       450
2          20160331       450
2          20160431       450
3          20160331       500
3          20160431       500
4          20160431       150

我希望决赛桌看起来像这样:

DocumentDate NetFinanced
2016-01-01   750
2016-02-01   500
2016-03-01   150

我尝试过以下操作但它无法正常工作:

SELECT A.DocumentDate, SUM(B.NetFinanced)
 FROM A
 JOIN B on B.ContractId=A.DocumentId
GROUP BY A.DocumentDate

有什么想法吗?提前致谢

3 个答案:

答案 0 :(得分:1)

你可以使用不同的

SELECT  A.DocumentDate,
        SUM(B.NetFinanced)
FROM    A
        JOIN (SELECT    DISTINCT
                        ContractId,
                        NetFinanced
              FROM      B
             ) B ON B.ContractId = A.DocumentId
GROUP BY A.DocumentDate

如果NetFinanced金额按SnapshotTimeId

更改,则结果会有所不同

如果您想要最近的NetFinanced金额,可以使用Row_number()来订购这些值。

SELECT  A.DocumentDate,
        SUM(B.NetFinanced)
FROM    A
        JOIN (SELECT    ROW_NUMBER() OVER (PARTITION BY ContractId ORDER BY SnapshotTimeId DESC) Rn,
                        ContractId,
                        NetFinanced
              FROM      B
             ) B ON B.ContractId = A.DocumentId AND B.Rn = 1
GROUP BY A.DocumentDate

答案 1 :(得分:0)

您在TableB中有NetFinanced的重复值,当然结果不会为您提供所需内容。您需要使用TableB中ContractIdNetFinanced列的唯一值(我假设)加入TableA:

SELECT A.DocumentDate,
       SUM(B.NetFinanced) NetFinanced
FROM dbo.TableA A
INNER JOIN (SELECT DISTINCT ContractId, NetFinanced
            FROM dbo.TableB) B
    ON A.DocumentId = B.ContractId
GROUP BY A.DocumentDate;

答案 2 :(得分:0)

尝试这样

SELECT A.DocumentDate, SUM(B.NetFinanced)
FROM A
JOIN (SELECT MAX(ContractId) ContractId, MAX(SnapshotTimeId)SnapshotTimeId,
             MAX(NetFinanced)NetFinanced
      FROM B GROUP BY ContractId) B ON B.ContractId = A.DocumentId
GROUP BY A.DocumentDate