sql-server SQL Server两个计数之和大小写

kdfy810k  于 2022-10-31  发布在  SQL Server
关注(0)|答案(1)|浏览(182)

我正想总结这两个算例,却碰到了一些错误说:
数据行'tmp.Col1'在选取清单中无效,因为它未包含在汇总函式或GROUP BY子句中。
我尝试添加group by Col1,但它无法将Col1识别为列。

SELECT 
   Col1,
   Col2,
   SUM(Col3 + Col4) AS 'In_Progress'
FROM
(
   SELECT
      COUNT(case when IO_Account_Handler_Contact IS NULL THEN 1 ELSE 0 END) AS 'Col1',
      COUNT(case when Issuing_Country_Name ='U.S.A' AND Internal_status IN ('OPEN-RELEASED','OPEN-CORRECTED') THEN 1 ELSE 0 END) AS 'Col2',
      COUNT(case when Issuing_Country_Name ='U.S.A' AND Internal_status = 'For Issuance'  THEN 1 ELSE 0 END) AS 'Col3',
      COUNT(case when Issuing_Country_Name ='U.S.A' AND Internal_status = 'OPEN-ACCEPTED' AND Completed_Quality_Review IS NOT NULL  THEN 1 ELSE 0 END) AS 'Col4'
   FROM Sales_Market
) tmp
wwtsj6pe

wwtsj6pe1#

您需要添加:
按列1、列2分组
使它工作。不确定这是否是你想要的坚韧。当使用任何聚合(总和,最大值,最小值等),你将总是需要分组任何没有聚合。所以在你的情况下,两列不只是1。或者你也可以总和(col1)和总和(col2)。
因此,可以选择:

SELECT 
   sum(Col1),
   sum(Col2),
   SUM(Col3 + Col4) AS 'In_Progress'
FROM
(
   SELECT
      COUNT(case when IO_Account_Handler_Contact IS NULL THEN 1 ELSE 0 END) AS 'Col1',
      COUNT(case when Issuing_Country_Name ='U.S.A' AND Internal_status IN ('OPEN-RELEASED','OPEN-CORRECTED') THEN 1 ELSE 0 END) AS 'Col2',
      COUNT(case when Issuing_Country_Name ='U.S.A' AND Internal_status = 'For Issuance'  THEN 1 ELSE 0 END) AS 'Col3',
      COUNT(case when Issuing_Country_Name ='U.S.A' AND Internal_status = 'OPEN-ACCEPTED' AND Completed_Quality_Review IS NOT NULL  THEN 1 ELSE 0 END) AS 'Col4'
   FROM Sales_Market
) tmp

SELECT 
   Col1,
   Col2,
   SUM(Col3 + Col4) AS 'In_Progress'
FROM
(
   SELECT
      COUNT(case when IO_Account_Handler_Contact IS NULL THEN 1 ELSE 0 END) AS 'Col1',
      COUNT(case when Issuing_Country_Name ='U.S.A' AND Internal_status IN ('OPEN-RELEASED','OPEN-CORRECTED') THEN 1 ELSE 0 END) AS 'Col2',
      COUNT(case when Issuing_Country_Name ='U.S.A' AND Internal_status = 'For Issuance'  THEN 1 ELSE 0 END) AS 'Col3',
      COUNT(case when Issuing_Country_Name ='U.S.A' AND Internal_status = 'OPEN-ACCEPTED' AND Completed_Quality_Review IS NOT NULL  THEN 1 ELSE 0 END) AS 'Col4'
   FROM Sales_Market
) tmp
group by Col1,Col2

相关问题