我有一张桌子
date doctor patient
20-1-18 xx 11
20-1-18 xx 22
20-1-18 yy 33
21-1-18 zz 44
21-1-18 xx 55
21-1-18 yy 66
22-1-18 zz 77
我想展示每天看过不止一次患者的医生。连同患者姓名
预期产量
date doctor patient
20-1-18 xx 11
20-1-18 xx 22
但是我只得到这个
date doctor patient
20-1-18 xx 11
如何使其同时显示两个值
答案 0 :(得分:3)
如果使用的是SQL Server,这可能是解决方案:
select [date], doctor, patient from (
select [date], doctor, pateint,
count(*) over (partition by [date], doctor) cnt
from my_table
) a where cnt > 1
答案 1 :(得分:2)
您需要一个带有having
子句的子查询:
select *
from tab
where (date, doctor) in
(
select date, doctor
from tab
group by date, doctor
having count(1)>1
);
+-----------+-------+---------+
| date | doctor| patient |
+-----------+-------+---------+
| 2018-01-20| xx | 11 |
+-----------+-------+---------+
| 2018-01-20| xx | 22 |
+-----------+-------+---------+
答案 2 :(得分:2)
如果您的dbms不支持窗口功能,则可以编写一个子查询以通过COUNT
然后date,doctor
来获得self join
select t2.*
from
(
SELECT date,doctor,count(*) cn
FROM T
GROUP BY date,doctor
) t1 INNER JOIN T t2 on t1.date = t2.date and t1.doctor = t2.doctor
WHERE cn > 1
[结果] :
| date | doctor | patient |
|---------|--------|---------|
| 20-1-18 | xx | 11 |
| 20-1-18 | xx | 22 |