所以说我们有行
ID | Date
1 1/20
2 1/20
1 1/21
7 1/21
4 1/22
5 1/22
所以说我只想看到出现在1/20和1/21的ID。 这应该只给我ID 1,因为这是1/20和1/21中出现的唯一行。实现这一目标的最简单方法是什么?
我试过这样做:
Select ID, [date]
FROM t1
INNER JOIN (
SELECT ID, Count(*) countRow
FROM t1
Where [date] in(1/20, 1/21)
GROUP BY ID
having count(DISTINCT [Date]) > 1
) aa on t1.id = aa.id
我觉得这是实现这一目标的简单方法。有什么想法吗?
答案 0 :(得分:1)
你现在拥有的方式非常简单。使用exists()
的替代方法:
select
t.id
, t.date
from t
where t.date in (1/20, 1/21)
and exists (
select 1
from t as i
where i.id = t.id
and i.date <> t.date
and i.date in (1/20, 1/21)
)
答案 1 :(得分:1)
一种方法使用group by
和having
:
select id
from t1
where date in ('1/20', '1/21')
group by id
having count(distinct date) = 2;
当然,如果date
确实存储为日期,您应该将日期常量的格式修改为YYYY-MM-DD。
答案 2 :(得分:0)
SELECT ID FROM T1 WHERE Date = '1/20' AND EXISTS (
SELECT ID FROM T1 AS T2 WHERE T2.Date = '1/21' AND
T1.ID = T2.ID)
答案 3 :(得分:0)
不确定是否更好郎 你这样做是非常标准的 不确定为什么你需要列出那个条件
的日期如果ID,日期是唯一的,那么您可以使用count(*)
Select ID, [date]
FROM t1
INNER JOIN ( SELECT ID
FROM t1
Where [date] = 1/20
intersection
SELECT ID
FROM t1
Where [date] = 1/21
) aa
on t1.id = aa.id
Select ID, [date]
FROM t1
INNER JOIN ( SELECT ID
FROM t1 t1a
join t1 t1b
on t1a.ID = t1b.ID
and t1a.[date] = 1/20
and t1b.[date] = 1/21
) aa
on t1.id = aa.id
如果是id,则值是唯一的
select id, value
from (select id, value
, count(*) over (partition by id order by value) as cnt
from t
where value in ('a', 'b')
) td
where cnt = 2
order by id, value