作为sql的初学者,我在PostgreSQL中有一个如下表所示。
id product type occured_at
1 A 6 2017-03-17 10:21:22.935278
1 B 6 2017-04-17 10:21:22.941801
1 B 8 2017-04-17 10:21:22.935278
1 B 8 2017-05-17 10:21:22.935278
1 D 8 2017-06-17 10:21:22.935278
2 C 4 2017-04-24 10:21:22.938517
3 A 8 2017-04-27 10:21:22.941801
4 C 8 2017-09-17 10:21:22.941801
4 C 6 2017-09-17 10:21:22.941801
5 D 8 2017-09-17 10:21:22.941801
问题是我如何获得在同一天发生的不同类型的ID和产品。就像
id product
1 B
4 C
如果有人可以帮助我,我真的很感激:)
答案 0 :(得分:1)
SELECT product
FROM YourTable
GROUP BY product
date_trunc('dat', occured_at)
HAVING count(DISTINCT type) > 1
答案 1 :(得分:1)
自我加入是一种方法:
SELECT DISTINCT A.ID, A.Product
FROM YourTable A
JOIN YourTable B ON A.ID = B.ID
AND A.Product = B.Product
AND DATE(A.Occured_at) = DATE(B.Occured_at)
AND A.Type <> B.Type