获取日期范围内每天仅存在一次的唯一记录

时间:2019-09-01 14:13:20

标签: database postgresql

我有一种情况,我想提取在特定期间内每天仅存在一次且仅一次的设备ID(DID)。我尝试了不同的方法和分区,但似乎每天只能单独获取该数据(日期= X,但是我需要查询可以在X和Y之间放置日期的地方)

示例,这是数据:

DID date     
A   2019-01-01
A   2019-01-01
A   2019-01-02
A   2019-01-03
B   2019-01-01
B   2019-01-02
B   2019-01-03
C   2019-01-01
C   2019-01-02
C   2019-01-02
C   2019-01-03
D   2019-01-01
D   2019-01-02
D   2019-01-03

查询应仅返回B&D(因为B&D从01到03每天存在一次) 我也希望得到计数,在这种情况下为2

谢谢!

2 个答案:

答案 0 :(得分:2)

您希望设备在该时段的每个日仅一次存在,因此,如果您group by did需要返回did count(date)count(distinct date)等于该时间段的天数:

select did
from tablename
where date between cast('2019-01-01' as date) and cast('2019-01-03' as date)
group by did
having 
  count(distinct date) = cast('2019-01-03' as date) - cast('2019-01-01' as date) + 1
  and
  count(date) = cast('2019-01-03' as date) - cast('2019-01-01' as date) + 1

请参见demo
或者:

select t.did
from (
  select did, date
  from tablename
  where date between cast('2019-01-01' as date) and cast('2019-01-03' as date)
  group by did, date
  having count(*) = 1
)t  
group by t.did
having count(*) = cast('2019-01-03' as date) - cast('2019-01-01' as date) + 1

请参见demo
结果:

| did |
| --- |
| B   |
| D   |

答案 1 :(得分:1)

一个选择是用DID进行聚合,并断言总计数等于不同日期的计数。如果此断言通过,则意味着给定的DID仅具有不同的日期。

SELECT DID
FROM yourTable
GROUP BY DID
HAVING COUNT(date) = COUNT(DISTINCT date);

Demo

如果要获取匹配的DID的总数,则可以对上面的子查询进行取COUNT(*)。或者,如果您想使用相同的查询,则可以尝试:

SELECT DID, COUNT(*) OVER () AS total_cnt
FROM yourTable
GROUP BY DID
HAVING COUNT(date) = COUNT(DISTINCT date);