如何选择在postgresql中多次出现多列值的所有行?
如何选择在postgresql中多次出现多列值的所有行? 我想找到具有相同产品id和输入日期的行如何选择在postgresql中多次出现多列值的所有行?,sql,postgresql,Sql,Postgresql,如何选择在postgresql中多次出现多列值的所有行? 我想找到具有相同产品id和输入日期的行 Input: id product_id entry_date product_name stock 1 009 2020-12-11 02:05:20.09876 apple 5 2 001 2020-12-11 03:04:10.09876 orange 9 3
Input:
id product_id entry_date product_name stock
1 009 2020-12-11 02:05:20.09876 apple 5
2 001 2020-12-11 03:04:10.09876 orange 9
3 004 2020-12-11 10:05:20.09876 pineapple 4
4 002 2020-12-11 02:05:20.09876 berry 5
5 009 2020-12-11 02:05:20.09876 apple 2
6 004 2020-12-11 10:05:20.09876 pineapple 1
7 006 2020-12-11 10:05:20.09876 pineapple 4
select * from
( select *,
count(1) over (partition by entry_date and product_id ) as occurs
from sale_order where entry_date::text LIKE '2020-12-11%'
) AS t where occurs > 1 ;
Output:
id product_id entry_date product_name stock
1 009 2020-12-11 02:05:20.09876 apple 5
3 004 2020-12-11 10:05:20.09876 pineapple 4
5 009 2020-12-11 02:05:20.09876 apple 2
6 004 2020-12-11 10:05:20.09876 pineapple 1
使用窗口函数-计数如下
select * from
(select t.*,
count(1) over (partition by product_id, entry_Date) as cnt
from t) t
where cnt > 1
您还可以按如下方式使用exists:
select * from t
where exists
(select 1 from t tt
where t.product_id = tt.product_id
and t.entry_Date = tt.entry_date
and t.id <> tt.id)
您使用COUNT window函数的方法非常正确-只需稍微更改语法并替换为
此外:
您可以简单地将时间戳转换为日期,而不是使用字符串操作过滤日期:
WHERE entry_date::date = '2020-12-11'
那么问题到底是什么呢?您共享的SQL是否没有生成给定的输出?如果它解决了您的问题,那么您可以接受答案,以便将此问题标记为已解决。
WHERE entry_date::date = '2020-12-11'