[英]I have two select queries combined using UNION. I am getting two results in one column how can I get it in two columns
I have two select queries combined using UNION. 我有两个选择查询结合使用UNION。 I am getting two results in one column but I want to get it in two Columns 我在一列中得到两个结果,但我想在两列中得到它
(SELECT count (*) As ServiceCreatedInOneMonth FROM [workAiderWinNe].[DynamicServiceDataOfClient] WHERE CreateDate > DATEADD(month, -1, GETDATE()) and CompanyID = 1 ) UNION ALL
(SELECT count (*) As ServiceCompletedInOneMonth FROM [workAiderWinNe].[DynamicServiceDataOfClient] WHERE CreateDate > DATEADD(month, -1, GETDATE()) AND IsCompleted =1 and CompanyID = 1)
you can simplify that into one single select query. 您可以将其简化为一个选择查询。 Use CASE WHEN
to check for IsCompleted
使用CASE WHEN
检查IsCompleted
SELECT count (*) As ServiceCreatedInOneMonth,
sum (case when IsCompleted = 1 then 1 else 0 end) As ServiceCompletedInOneMonth
FROM [workAiderWinNe].[DynamicServiceDataOfClient]
WHERE CreateDate > DATEADD(month, -1, GETDATE())
and CompanyID = 1
Use subqueries: 使用子查询:
SELECT
(SELECT count (*)
FROM [workAiderWinNe].[DynamicServiceDataOfClient]
WHERE CreateDate > DATEADD(month, -1, GETDATE())
AND CompanyID = 1 ) ServiceCreatedInOneMonth ,
(SELECT count (*)
FROM [workAiderWinNe].[DynamicServiceDataOfClient]
WHERE CreateDate > DATEADD(month, -1, GETDATE())
AND IsCompleted =1 and CompanyID = 1) ServiceCompletedInOneMonth
One option is to add null as ServiceCompletedInOneMonth
as the second column of your first query, null as ServiceCreatedInOneMonth
as the first column of your second query, then union. 一种选择是增加null as ServiceCompletedInOneMonth
的第一个查询的第二列, null as ServiceCreatedInOneMonth
为你的第二个查询的第一列,然后结合。 Note that parentheses are not needed with union: 请注意,并不需要括号:
SELECT count (*) As ServiceCreatedInOneMonth,null as ServiceCompletedInOneMonth
FROM [workAiderWinNe].[DynamicServiceDataOfClient]
WHERE CreateDate > DATEADD(month, -1, GETDATE()) and CompanyID = 1
UNION ALL
SELECT null as ServiceCreatedInOneMonth,count (*) As ServiceCompletedInOneMonth
FROM [workAiderWinNe].[DynamicServiceDataOfClient]
WHERE CreateDate > DATEADD(month, -1, GETDATE()) AND IsCompleted =1 and CompanyID = 1
Note: I wrote this without checking the query. 注意:我编写此代码时没有检查查询。 Squirrel's answer is best. 松鼠的答案是最好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.