我有两个使用UNION组合的选择查询。我在一列中得到两个结果,但我想在两列中得到它
(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)
答案 0 :(得分:2)
您可以将其简化为一个选择查询。使用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
答案 1 :(得分:1)
使用子查询:
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
答案 2 :(得分:0)
一个选择是将null as ServiceCompletedInOneMonth
添加为第一个查询的第二列,
null as ServiceCreatedInOneMonth
作为第二个查询的第一列,然后合并。请注意,并不需要用括号括起来:
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
注意:我编写此代码时没有检查查询。松鼠的答案是最好的。