在同一个查询中计数和求和

时间:2014-01-13 12:06:43

标签: sql tsql sql-server-2005

我有我的疑问:

SELECT CASE WHEN dt.value = 380 AND p.FlowStatusID <> 5 THEN 'FATTURE C&S'  
            WHEN dt.value = 381 AND p.FlowStatusID <> 5 THEN 'NOTE CREDITO C&S' 
            WHEN dt.value = 380 OR dt.value = 381 AND p.FlowStatusID = 5 THEN 'LATE ARCHIVE C&S' 
            END AS [Tipo Documento]
            ,SUM(p.SystemField5) AS 'Nr Pagine', Count(p.SystemField3) AS 'Nr Documenti' 

FROM dbo.PSDOC p INNER JOIN dbo.listDocumentTypes dt ON p.DocumentTypeId = dt.value

GROUP BY dt.value, p.FlowStatusID

我希望按文档类型

获取总和和计数组
 document type      |   sum         |   count
--------------------------------------------------
FATTURE C&S         |               |
NOTE CREDITO C&S    |               |
LATE ARCHIVE C&S    |               |

但是查询结果

document type        sum         count
----------------------------------------------
LATE ARCHIVE C&S    |   8      |   5
FATTURE C&S         |   2412   |   1265
FATTURE C&S         |   104254 |   67990
NOTE CREDITO C&S    |   362    |   236
FATTURE C&S         |   167    |   98
LATE ARCHIVE C&S    |   4      |    2
LATE ARCHIVE C&S    |   297107 |   163797

如何在文档类型列中将其设置为不同?

1 个答案:

答案 0 :(得分:2)

dt.value中删除FlowStatusIdgroup by,并将其替换为完整的case语句:

SELECT CASE WHEN dt.value = 380 AND p.FlowStatusID <> 5 THEN 'FATTURE C&S'  
            WHEN dt.value = 381 AND p.FlowStatusID <> 5 THEN 'NOTE CREDITO C&S' 
            WHEN dt.value = 380 OR dt.value = 381 AND p.FlowStatusID = 5 THEN 'LATE ARCHIVE C&S' 
            END AS [Tipo Documento],
       SUM(p.SystemField5) AS "Nr Pagine", Count(p.SystemField3) AS "Nr Documenti"
FROM dbo.PSDOC p INNER JOIN
     dbo.listDocumentTypes dt
     ON p.DocumentTypeId = dt.value
GROUP BY CASE WHEN dt.value = 380 AND p.FlowStatusID <> 5 THEN 'FATTURE C&S'  
              WHEN dt.value = 381 AND p.FlowStatusID <> 5 THEN 'NOTE CREDITO C&S' 
              WHEN dt.value = 380 OR dt.value = 381 AND p.FlowStatusID = 5 THEN 'LATE ARCHIVE C&S' 
        END