Transact-SQL子查询

时间:2014-02-14 11:13:15

标签: sql excel tsql

我很难找到如何完成子查询的逻辑,或者至少我认为是必需的!我会展示我拥有的东西:

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

我想要做的是我已经完成了CH2我需要指定它以C结尾,状态列是空白还是C并且通过做一个非常统计的CHNO和C一起给我结果我需要但我不能为我的生活找到如何写它!

我正在使用Microsoft Query将其数据源中的数据直接导入Excel电子表格。

非常感谢您看一看。

2 个答案:

答案 0 :(得分:1)

自从我使用MS Query以来已经很久了,所以我对语法模糊不清,但这是如何编写包含WHERE子句和聚合的子查询的一般想法,以帮助您入门:

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

答案 1 :(得分:0)

如果您只想知道CH.STATUS = 'C'的记录数,而不是添加COUNTCASE语句的COUNT(CASE WHEN CH.STATUS = 'C' then 1 else null end) as 'COMPLETED CH2'语句。

COUNT

在合并CASENULL语句时,请记住ELSE语句为SUM,否则将计算所有行。

作为替代方案,您可以使用SUM(CASE WHEN CH.STATUS = 'C' then 1 else 0 end) as 'COMPLETED CH2'

执行此操作

{{1}}