简体   繁体   中英

Transact-SQL Sub Query

I'm struggling to find the logic of how to accomplish a sub query, or at least that's what I think is required! I'll show what I have:

SELECT  CH.SFA, 
        convert(datetime, RE.START_DATE, 103) AS 'START DATE', 
        Count(Distinct CH.CHNO) AS 'TOTAL CH', 
        Count(CH.STATUS) AS 'COMPLETED CH', 
        count(distinct  CH.CHNO +  CH.STATUS) As 'COMPLETED CH2'
FROM CUSTOMER.dbo. CH  CH, CUSTOMER.dbo.RE RE
WHERE 
      RE.SFA = CH.SFA
GROUP BY  
      CH.SFA, RE.START_DATE

What I am trying to do is where I have COMPLETED CH2 I need to specify that it ends with a C, the Status Column is either blanks or C's and by doing a distinct count of CHNO and C together give me the result I need but I cannot for the life of me find out how to write it!

I am using Microsoft Query to take the data from its source straight into the Excel spreadsheet.

Many thanks for taking a look.

Been ages since I've used MS Query so I'm fuzzy on syntax, but this is the general idea of how to write a subquery containing a WHERE clause and an aggregation to get you started:

SELECT  
    CH.SFA, 
    convert(datetime, RE.START_DATE, 103) AS 'START DATE', 
    Count(DISTINCT CH.CHNO) AS 'TOTAL CH', 
    Count(CH.STATUS) AS 'COMPLETED CH',
    CCH.COMPLETED_CH2 AS 'COMPLETED CH2'
FROM CUSTOMER.dbo.CH CH
INNER JOIN CUSTOMER.dbo.RE RE
    ON RE.SFA = CH.SFA
LEFT JOIN (
    SELECT SFA, COUNT(DISTINCT CH.CHNO) AS COMPLETED_CH2
    FROM CUSTOMER.dbo.CH
    WHERE STATUS = 'C'
    GROUP BY SFA
) AS CCH
    ON RE.SFA = CCH.SFA
GROUP BY CH.SFA, RE.START_DATE

if you just want to know count of records where CH.STATUS = 'C' than add another COUNT statement with CASE logic.

COUNT(CASE WHEN CH.STATUS = 'C' then 1 else null end) as 'COMPLETED CH2'

when combining COUNT and CASE statement remember to have NULL for ELSE statement, otherwise all rows will be counted.

as an alternative you can do it with a SUM

SUM(CASE WHEN CH.STATUS = 'C' then 1 else 0 end) as 'COMPLETED CH2'

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