首页 > 解决方案 > 无法计算出可以得到我想要的结果的 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 方面还算不错,但我就是无法理解这一点。

标签: sqlsql-servertsql

解决方案


您可以轻松地将 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

推荐阅读