sql - 无法计算出可以得到我想要的结果的 SQL 查询
问题描述
所以我有一张看起来像这样的表格:
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 方面还算不错,但我就是无法理解这一点。
解决方案
您可以轻松地将 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
推荐阅读
- php - 检查数组中的哪一个值在字符串 PHP 中
- javascript - 使用 nodemailer 发送电子邮件卡在 Ubuntu 16.04 上
- android - 将“FlexBoxLayout”添加到项目会中断编译
- c# - 实体框架无法检索记录
- python - 操作系统和子进程不再在 Windows 10 上找到二进制文件
- sql - 在 SQL 中计算不同日期之间 sum() 的差异
- mysql - select * from table1 where user_id in(select id from users where name like '%name%')
- go - 如何使用 logpacker 包 paypal 进行信用卡支付?
- python - 在 Python 崩溃的地方启动代码
- sql - 使用 SQL 从 url 中剥离域名