我正在尝试使用两个列(Item, Customer
)获取类似数据,根据以下查询,我没有获得重复数据的第一个值。
请帮助我获得如下所示的预期结果。
示例数据
+------+------------+-----------+----------+
| E_ID | E_Date | Item | Customer |
+------+------------+-----------+----------+
| 1 | 10/10/2017 | Microsoft | DIB |
| 2 | 10/11/2017 | Oracle | UNB |
| 3 | 10/12/2017 | IBM | UNB |
| 4 | 10/13/2017 | Microsoft | DIB |
| 5 | 10/14/2017 | Oracle | UNB |
| 6 | 10/15/2017 | SAP | DIB |
| 7 | 10/15/2017 | Microsoft | DIB |
+------+------------+-----------+----------+
我的剧本
SELECT * FROM
(
SELECT E_ID, E_Date,Item,Customer,
Row_Number() OVER(PARTITION BY Customer,Item ORDER By E_ID)AS Rank
FROM Events
) AS B WHERE Rank > 1
预计结果为
+------+------------+----------+----------+
| E_ID | E_Date | Item | Customer |
+------+------------+----------+----------+
| 1 | 10/10/2017 | Mirosoft | DIB |
| 4 | 10/13/2017 | Mirosoft | DIB |
| 7 | 10/15/2017 | Mirosoft | DIB |
| 2 | 10/11/2017 | Oracle | UNB |
| 5 | 10/14/2017 | Oracle | UNB |
+------+------------+----------+----------+
我的实际结果
+------+------------+-----------+----------+------+
| E_ID | E_Date | Item | Customer | Rank |
+------+------------+-----------+----------+------+
| 4 | 10/13/2017 | Microsoft | DIB | 2 |
| 7 | 10/15/2017 | Microsoft | DIB | 3 |
| 5 | 10/14/2017 | Oracle | UNB | 2 |
+------+------------+-----------+----------+------+
答案 0 :(得分:3)
如果我读得正确,您应该使用COUNT
代替ROW_NUMBER
:
SELECT * FROM
(
SELECT E_ID, E_Date, Item, Customer,
COUNT(*) OVER (PARTITION BY Customer, Item) AS cnt
FROM Events
) t
WHERE cnt > 1
ORDER BY Item, Customer;
上述查询将返回该组中具有多个记录的每个客户/项目组的记录。
答案 1 :(得分:0)
有很多方法可以做到这一点,一种方法是使用下面的EXISTS子句
SELECT
E.E_ID, E.E_Date,E.Item,E.Customer
FROM Events E WHERE EXISTS
(
SELECT 1
FROM Events E1
WHERE
E1.E_ID<>E.E_ID
AND E.Item=E1.Item
AND E.Customer=E1.Customer
)
答案 2 :(得分:0)
修改了一下你的查询
join