有没有办法通过重构此SQL查询来检索不同的结果(基于ID)?

时间:2016-08-18 12:47:26

标签: sql sql-server count distinct

此查询检索多个计数,第一个计数是基于" maintid"的不同计数。有没有办法根据maintID使其他计数不同,而他们也在寻找type / enteredby?

SELECT 
    datepart(mm, m.creationdate) AS themonth, 
    datepart(yyyy, m.creationdate) AS theyear, 
    count(DISTINCT m.maintid) AS total, 
    count(nullif(m.thetype, '1')) AS regular, 
    count(nullif(m.thetype, '2')) AS multi, 
    count(nullif(m.thetype, 11)) AS quick, 
    count(nullif(m.enteredby, 'WriteMonthly')) AS wm, 
    Count(case when m.thetype=10 then 1 else null end) as Errors,         
    Count(case when m.thetype=12 then 1 else null end) as FOH 
FROM 
    Maintlist AS m 
RIGHT JOIN 
    TypeList AS t ON t.typekey = m.thetype 
LEFT JOIN 
    MaintNotes AS mn ON m.maintid = mn.maintid 
WHERE 
    mn.enteredby in ('210', '181', '229', '240', '266', '284', '291', '238', '239', '272', '273') 
GROUP BY 
    datepart(mm, m.creationdate), datepart(yyyy, m.creationdate) 
ORDER BY 
    datepart(yyyy, m.creationdate) DESC, datepart(mm, m.creationdate) DESC

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您希望计算不同的MaintId。如果是这样的话:

SELECT datepart(month, m.creationdate) AS themonth,
       datepart(year, m.creationdate) AS theyear, 
       count(DISTINCT m.maintid) AS total, 
       count(distinct case when m.thetype <> 1 then m.maintid end) as regular,
       count(distinct case when m.thetype <> 2 then m.maintid end) as multi,
       count(distinct case when m.thetype <> 11 then m.maintid end) as quick,
       count(distinct case when m.enteredby <> 'WriteMonthly' then m.maintid end) AS wm, 
       . . .

这是您逻辑的直接翻译。但是,我很确定你打算:

       count(distinct case when m.thetype = 1 then m.maintid end) as regular,

而不是:

       count(distinct case when m.thetype <> 1 then m.maintid end) as regular,