COUNT()将两个单独的列计数相乘,我如何才能实现这一点?

时间:2017-10-25 20:36:33

标签: sql count ssms aggregate-functions

以下是表格: 客户

custid(PK) custname custtype
001        john     null
002        rob      1

CITY

cityid(PK) cityname
001        Baltimore
002        Knoxville

PACKAGE

packageid(PK) custid(PK,FK) cityid
001           001           001
001           002           001
002           001           002

现在我的查询是:

SELECT DISTINCT CITYNAME, CUSTTYPE, COUNT(P.PACKAGEID) AS PACKAGE_COUNT
FROM CITY S LEFT OUTER JOIN PACKAGE P 
ON S.CITYID=P.CITYID,
CUSTOMER C INNER JOIN PACKAGE Q 
ON C.CUSTID=Q.CUSTID
GROUP BY CITYNAME, CUSTTYPE;

结果:

CITYNAME  CUSTTYPE PACKAGE_COUNT
BALTIMORE NULL     4
KNOXVILLE NULL     2
BALTIMORE 1        2
KNOXVILLE 1        0

我希望看到的是:

CITYNAME  CUSTTYPE PACKAGE_COUNT
BALTIMORE NULL     1
KNOXVILLE NULL     1
BALTIMORE 1        1
KNOXVILLE 1        0

据我所知,cityname计数乘以custtype计数,即baltimore = 2和null = 2因此2 * 2 = 4.即使在包表中,baltimore只从null custtype接收一个包。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

使用交叉连接生成所有行,然后执行左连接和聚合:

SELECT C.CITYNAME, CT.CUSTTYPE, COUNT(P.PACKAGEID) AS PACKAGE_COUNT
FROM CITY S CROSS JOIN
     (SELECT DISTINCT CUSTTYPE FROM CUSTOMER) CT LEFT OUTER JOIN
     PACKAGE P 
     ON S.CITYID = P.CITYID AND CT.CUSTID = P.CUSTID
GROUP BY C.CITYNAME, CT.CUSTTYPE;