选择具有特定日期且仅记录一次的所有用户

时间:2017-09-11 13:30:04

标签: sql teradata

我有这张桌子。

My Sql table in (SQL Fiddle)


ID       Date       Value 
___      ____       _____
3241     01/01/00   15456
3241     9/17/12    5
3241     9/16/12    100
3241     9/15/12    20
4355     01/01/00   01
4355     9/16/12    12
4355     9/15/12    132
4355     9/14/12    4
1001     01/01/00   456
1001     9/16/12    125
5555     01/01/00   01
1234     01/01/00   01
1234     9/16/12    45
2236     01/01/00   879
2236     9/15/12    128
2236     9/14/12    323
2002     01/01/00   567

我想,select所有记录01-01-00 as date并且只显示过一次。 我想要的结果如下表所示。


ID       Date       Value 
___      ____       _____
5555     01/01/00   01
2002     01/01/00   567

我尝试使用HAVING子句,但由于GROUP BY,结果是 错误 ,因为我的一个选择有多个记录对我的情况不利。

我的错误尝试:

SELECT * FROM
  (SELECT *
   FROM table1
   GROUP BY id, date, value
   HAVING count(Id)=1) t1
WHERE date='01-01-00'

Query Result (SQL Fiddle)

4 个答案:

答案 0 :(得分:1)

我会用:

select id, max(date) as date, max(value) as value
from t1
group by id
having max(date) = '01-01-00' and count(*) = 1;

更快的方法可能是:

select t1.*
from t1
where date = '01-01-00' and
      not exists (select 1 from t1 tt1 where tt1.id = t1.id and tt1.date <> '01-01-00');

这可以利用t1(date)t1(id, date)上的索引。

答案 1 :(得分:0)

使用IN

SELECT * 
FROM table1
WHERE id IN (
     SELECT id
     FROM table1
     GROUP BY id
     HAVING count(Id)=1
   ) and date='01-01-00'

答案 2 :(得分:0)

将您的查询更改为

SELECT * 
FROM
  (SELECT *
   FROM table1
   GROUP BY id
   HAVING count(id)=1) t1
WHERE t1.date='01-01-00'

答案 3 :(得分:0)

我只是没有注意到我在group by中犯了一个错误,而不只是ID,我把所有columns

SELECT * FROM 
  (SELECT *
   FROM Table1
   GROUP BY `ID`
   HAVING count(`ID`)=1) t1
WHERE `Date`='2000-01-01 00:00:00'

但是对于我的问题,我采用this solution from Gordon Linoff,因为它对我来说似乎更好。

PS:我有200万条记录。

相关问题