首页 > 解决方案 > 显示 if 子句是否从 SQL 中找到结果

问题描述

我在 tableexample 中有以下示例数据(我使用 MSSQL):

ID 日期 标签
15551 2021-11-10 1
15551 2021-11-09 0
15551 2021-11-10 1
12123 2021-11-09 1
12123 2021-11-09 1
15551 2021-11-10 1
12123 2021-11-10 1
74141 2021-11-10 1
12345 2021-11-10 1
11111 2021-11-10 1
74141 2021-11-10 1
12345 2021-11-10 0

现在我想获取一组 ID (15551,12123,12345,74141) 的信息,如果它们包含至少一个满足条件的条目:日期 <> 今天 (2021-11-10) 并且标签 = 1

所以我的这个例子的结果应该是这样的:

ID 检查发现条目
15551 0
12123 1
74141 0
12345 0

解释:12123 和 15551 包含从昨天 (2021-11-09) 开始的日期,但 15551 包含标签 = 0 的日期。因此只有 12123 至少满足一个结果的两个条件。

所以我很容易将它们分组在一起,但我不知道如何检查分组 ID 的条件:选择 ID,??? 作为 tableexample 中的 checkfoundentry 其中 ID 在 (15551,12123,12345,74141) 按 ID 分组

有可能这样做吗?

这是可以提供示例数据的sql:

Create Table table1 (
colID int,
coldate date,
coltag int
);

Insert Into table1 (colID, coldate, coltag)
values (15551, '2021-11-10', 1),
(15551, '2021-11-09', 0),
(15551, '2021-11-10', 1),
(12123, '2021-11-09', 1),
(12123, '2021-11-09', 1),
(15551, '2021-11-10', 1),
(12123, '2021-11-10', 1),
(74141, '2021-11-10', 1),
(12345, '2021-11-10', 1),
(11111, '2021-11-10', 1),
(74141, '2021-11-10', 1),
(12345, '2021-11-10', 0),
(12345, '2021-11-10', 1)

这是我发现的一个具体解决方案,你能告诉我这是否有用吗?

Select ID, (CASE when (Select sum(Tag) from table1 t where date <> 2021-11-10 and tag = 1 and s.ID = t.ID Group By ID) > 0 then 1 Else 0 END) as checkfoundentry from table1 s Group By ID

标签: sql-servergroupingcontains

解决方案


您可以使用window functions来计算每个 ID 的条件

with x as (
    select * ,
        Count(*) over(partition by id) cnt, 
        Sum(tag) over(partition by id) tg, 
        Count(case when date !='2021-11-10' then 1 end) over(partition by id) dt
    from t
    where t.ID in (15551,12123,12345,74141)
)
select distinct id, 
    case when dt>0 and cnt=tg then 1 else 0 end CheckFoundEntry
from x;

推荐阅读