排除除一个不同字段之外的重复记录

时间:2016-09-15 04:42:23

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

我有一个包含客户编号,日期,金额和交易类型(买入或卖出)的交易清单。我只想退回未被同一客户,日期和金额抵消但交易类型相反的交易(每位客户,每天,每金额)。

例如,我的样本表(交易)如下:

+----------+------------+--------+--------+
| Customer |    Date    | Amount | Action |
+----------+------------+--------+--------+
|     1111 | 15/09/2016 |      5 | Buy    |
|     2222 | 15/09/2016 |      5 | Sell   |
|     3333 | 15/09/2016 |      6 | Buy    |
|     3333 | 15/09/2016 |      6 | Sell   |
|     4444 | 15/09/2016 |      7 | Sell   |
|     2222 | 15/09/2016 |      6 | Buy    |
+----------+------------+--------+--------+

我只想要返回以下项目:

+----------+------------+--------+--------+
| Customer |    Date    | Amount | Action |
+----------+------------+--------+--------+
|     1111 | 15/09/2016 |      5 | Buy    |
|     2222 | 15/09/2016 |      5 | Sell   |
|     4444 | 15/09/2016 |      7 | Sell   |
|     2222 | 15/09/2016 |      6 | Buy    |
+----------+------------+--------+--------+

客户3333因为在同一天的买入和卖出金额相同而被排除在外。即使客户2222在同一天进行了买卖,客户2222也被留在了不同的位置,所以我需要两个记录才能返回。

1 个答案:

答案 0 :(得分:2)

这就足够了:

SELECT Customer, Date, Amount, MAX(Action) Action
FROM Src
GROUP BY Customer, Date, Amount
HAVING COUNT(*)=1

测试用例

WITH Src AS
(
    SELECT * FROM (VALUES
    (1111, '15/09/2016', 5, 'Buy'),
    (2222, '15/09/2016', 5, 'Sell'),
    (3333, '15/09/2016', 6, 'Buy'),
    (3333, '15/09/2016', 6, 'Sell'),
    (4444, '15/09/2016', 7, 'Sell'),
    (2222, '15/09/2016', 6, 'Buy')
    ) T(Customer, Date, Amount, Action)
)
SELECT Customer, Date, Amount, MAX(Action) Action
FROM Src
GROUP BY Customer, Date, Amount
HAVING COUNT(*)=1

<强>结果

Customer    Date       Amount      Action
----------- ---------- ----------- ----
1111        15/09/2016 5           Buy
2222        15/09/2016 5           Sell
2222        15/09/2016 6           Buy
4444        15/09/2016 7           Sell