所以我有一个看起来像这样的表:
ReferralId EpisodeId DateOfReferral Hospital
1 1 20/04/2019 1
2 1 21/04/2019 2
3 2 28/04/2019 2
4 2 24/04/2019 3
5 2 24/04/2019 1
6 3 22/04/2019 1
7 3 24/04/2019 4
我正在尝试查询该表,以带回在同一日期具有多个推荐人的EpisodeId,但是这两个推荐人具有不同的医院。因此,上表的结果将是:
EpisodeId
2
在SQL方面,我还不错,但是我无法忍受这个问题。
答案 0 :(得分:2)
为此,您可以轻松使用具有不同计数的HAVING。
您还应该使用正确的数据类型。将日期存储为字符串不是一个好主意。 https://sqlblog.org/2009/10/12/bad-habits-to-kick-choosing-the-wrong-data-type
declare @Something table
(
ReferralId int
, EpisodeId int
, DateOfReferral varchar(20)
, Hospital int
)
insert @Something values
(1, 1, '20/04/2019', 1)
, (2, 1, '21/04/2019', 2)
, (3, 2, '28/04/2019', 2)
, (4, 2, '24/04/2019', 3)
, (5, 2, '24/04/2019', 1)
, (6, 3, '22/04/2019', 1)
, (7, 3, '24/04/2019', 4)
select EpisodeID
from @Something s
group by EpisodeId
, DateOfReferral
having count(distinct Hospital) > 1
答案 1 :(得分:2)
如果您只想观看剧集,而不想要日期或医院,那么这是select distinct
与group by
一起使用的罕见情况之一:
select distinct EpisodeID
from t
group by EpisodeId, DateOfReferral
having count(distinct Hospital) > 1;
或者,您可以在不进行汇总的情况下执行此操作:
select distinct EpisodeID
from t
where exists (select 1
from t t2
where t2.EpisodeId = t.EpisodeId and
t2.DateOfReferral = t.DateOfReferral and
t2.Hospital <> t.Hospital
);
此版本尤其可以利用(EpisodeId, DateOfReferral, Hospital)
上的索引,这可能比GROUP BY
的方法更快。
答案 2 :(得分:1)
:cs f filename.c s symbol
(我在智能手机上输入的速度太慢-刚注意到这与之前的答案相同,而我刚开始的时候就没有。)