如何在单个选择语句中向多个count()函数添加条件

时间:2019-06-28 11:50:37

标签: sql sql-server tsql

好的,这就是我尝试过的:

SELECT 
    DISTINCT [TRANSPORT ADDRESS] AS BUYERS, 
    CASE WHEN FRANCHISE = 'FRANCHISE' THEN COUNT(DISTINCT ORDERID) END AS [FRANCHISE],
    CASE WHEN FRANCHISE = 'OWN' THEN COUNT(DISTINCT ORDERID) END AS [OWN]
FROM JOINED
GROUP BY [TRANSPORT ADDRESS]
ORDER BY [TRANSPORT ADDRESS]

我收到以下错误:

Column 'JOINED.Franchise' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

count()函数显然缺少分组,我只是不知道将其添加到哪里,或者甚至有可能以这种方式添加。

我也尝试过更冗长的方式:

SELECT T1.BUYERS, [FRANCHISE SALES], [OWN SALES] 
FROM
    (SELECT DISTINCT [TRANSPORT ADDRESS] AS BUYERS, COUNT(DISTINCT ORDERID) AS [FRANCHISE SALES]
    FROM JOINED
    WHERE FRANCHISE = 'FRANCHISE'
    GROUP BY TRANSPORT ADDRESS]) 
T1
FULL OUTER JOIN
    (SELECT DISTINCT [TRANSPORT ADDRESS] AS BUYERS, COUNT(DISTINCT ORDERID) AS [OWN SALES]
    FROM JOINED
    WHERE FRANCHISE = 'OWN'
    GROUP BY [TRANSPORT ADDRESS]) 
T2
ON T1.BUYERS = T2.BUYERS
ORDER BY T1.BUYERS

但我不想合并两个“买方”属性,以使所有买方都集中在一个栏中。我想我应该在此解决方案中使用UNION,但这会使我做更多的重命名和手动选择。

所以我想知道我是否可以像第一种更简洁的方式那样做。

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合,将CASE作为COUNT()的参数:

SELECT [TRANSPORT ADDRESS] AS BUYERS, 
       COUNT(DISTINCT CASE WHEN FRANCHISE = 'FRANCHISE' THEN ORDERID END) AS [FRANCHISE],
       COUNT(DISTINCT CASE WHEN FRANCHISE = 'OWN' THEN ORDERID END) AS [OWN]
FROM JOINED
GROUP BY [TRANSPORT ADDRESS]
ORDER BY [TRANSPORT ADDRESS];

请注意,SELECT DISTINCT几乎永远不适用于GROUP BY

答案 1 :(得分:0)

@Gordon Linoff是正确的。但是我要对@Gordon Linoff进行一点修改。假设可能缺少FRANCHISE'OWN'或'FRANCHISE'

SELECT [TRANSPORT ADDRESS] AS BUYERS, 
           COUNT(DISTINCT CASE WHEN FRANCHISE = 'FRANCHISE' THEN ORDERID Else 0 END) AS [FRANCHISE],
           COUNT(DISTINCT CASE WHEN FRANCHISE = 'OWN' THEN ORDERID Else 0 END) AS [OWN]
    FROM JOINED
    GROUP BY [TRANSPORT ADDRESS]
    ORDER BY [TRANSPORT ADDRESS];

我不清楚。您想要特许经营的总数吗?根据我的假设代码将是.....

SELECT [TRANSPORT ADDRESS] AS BUYERS, 
               COUNT(DISTINCT CASE WHEN FRANCHISE = 'FRANCHISE' THEN ORDERID Else 0 END) AS [FRANCHISE],
               COUNT(DISTINCT CASE WHEN FRANCHISE = 'OWN' THEN ORDERID Else 0 END) AS [OWN],(select count(ORDERID ) from JOINED) as AllFRANCHISE 
        FROM JOINED
        GROUP BY [TRANSPORT ADDRESS]
        ORDER BY [TRANSPORT ADDRESS];