sql-server - 多日期范围查询
问题描述
我必须根据日期范围从一张表中收集数据。现在正在使用多项选择查询来获取此计数 Ex
Select @count1 = count(*)
from table
where createddate between @date1 and @date2 and status in (1,2)
Select @count2 = count(*)
from table
where createddate between @date2 and @date3 and status in (3,4)
Select @count23 = count(*)
from table
where createddate between @date3 and @date4 and status in (5,6)
Select count1, count2, count3
如何合并以上 3 个查询?它会提高性能吗?
解决方案
使用条件聚合:
SELECT COUNT(CASE WHEN createdate BETWEEN @Date1 AND @Date2 AND [Status] IN (1,2) THEN 1 END) AS Count1,
COUNT(CASE WHEN createdate BETWEEN @Date2 AND @Date3 AND [Status] IN (3,4) THEN 1 END) AS Count2
FROM dbo.YourTable;
推荐阅读
- ddev - 如何在 ddev 的容器中设置环境变量?
- javascript - 创建数字数组的函数式方法
- c# - 选择 TOP 5 通过代码调用时只返回一行,其中相同的脚本在 SQL Server 中返回 5 行
- reactjs - 如何从谷歌分析中检索 UTM 源?- 反应
- ios - Swift 4 中的委托模式不起作用!谁能解释 Swift 4 中正确的委托模式?
- qt - QSlider 在 UI 上明显滞后
- node.js - 对话框委托指令状态不变
- c++ - 定义 constexpr 静态数据成员
- crystal-reports-2013 - Crystal Report - 运行总计字段的值列表?
- java - 无法使用 Java 10.0.1 运行 Eclipse