sql-server - 显示 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
解决方案
您可以使用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;
推荐阅读
- javascript - 如何让模态弹出窗口显示在图库中单击的图像?
- excel - 在excel中设置动态列引用
- c# - 如何使用 Tokenizer 解析 WhoIs 数据
- php - Mysql 查询在 AWS 服务器的生产中加载时间过长
- java - 如何在 java 的 rest 调用中将 Map 作为 requestBody 发送
- python - 为什么在创建类的实例时得到元组而不是整数?
- javascript - 如何在鼠标悬停时在 angularjs 中显示图像?
- node.js - 尝试使用 NodeJS 和 Express 导入 OL5 时出错
- java - 没有使用 java mysql 将记录添加到数据库中
- ftp - Nifi 通知/等待在完成 ftp 下载后通知另一个处理器链