将同一个 table 中的 3 select 语句组合成 sql 中的 1 table

combine 3 select statment from the same table into 1 table in sql

我正在尝试 运行 3 个不同的 select query on 1 table 其中我 return created 的计数, 已完成待处理 任务基于 created_datemodified_date 我可以根据字段 [=] 在 modified_date 中区分 donepending 25=]状态

当我 运行 每个单独查询它 return 正确答案。

但我想要的是将这 3 个查询合并为一个 table,如下所示:

+---------------------- +------------------+---------------------+
|  Total_created_files  | Total_done_files | Total_pending_files |
+-----------------------+------------------+---------------------+
|          14           |         40       |         9           | 
+-----------------------+------------------+---------------------+          

代码:

select 
count([create_date]) as Total_created_files
FROM [TEC_APP].[dbo].[case_to_do]
where  [create_date] >='2022-05-01 00:00:00.000'
AND
CAST([create_date] AS date) <=  CAST(GETDATE() AS date)

select 
count([modified_date]) as Total_done_files
FROM [TEC_APP].[dbo].[case_to_do]
where  [modified_date] >='2022-05-01 00:00:00.000'
AND
CAST([modified_date] AS date) <=  CAST(GETDATE() AS date)
AND
status = 'DONE'

select 
count([modified_date]) as Total_pending_files
FROM [TEC_APP].[dbo].[case_to_do]
where  [modified_date] >='2022-05-01 00:00:00.000'
AND
CAST([modified_date] AS date) <=  CAST(GETDATE() AS date)
AND
status = 'Pending'                                                  

case expression 使用条件聚合:

SELECT SUM(case when <First Condition here> then 1 else 0 end) as Total_created_files,
       SUM(case when <Second Condition here> then 1 else 0 end) as Total_done_files,
       SUM(case when <Third Condition here> then 1 else 0 end) as Total_pending_files
FROM [TEC_APP].[dbo].[case_to_do]

根据需要使用条件聚合 COUNT。我在这里做了几个假设,但这应该是你所追求的:

USE TEC_APP;
GO

SELECT COUNT(CASE WHEN [create_date] < DATEADD(DAY,1,CONVERT(date,GETDATE())) THEN 1 END) AS Total_created_files,
       COUNT(CASE WHEN [modified_date] >= '20220501' AND [modified_date] < DATEADD(DAY,1,CONVERT(date,GETDATE())) AND Status = 'DONE' THEN 1 END) AS Total_done_files,
       COUNT(CASE WHEN [modified_date] >= '20220501' AND [modified_date] < DATEADD(DAY,1,CONVERT(date,GETDATE())) AND Status = 'Pending' THEN 1 END) AS Total_pending_files
FROM [dbo].[case_to_do]
WHERE create_date >= '20220501'; --Presumably something can't be modified before it's created.