简体   繁体   中英

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. 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

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM