如何跨多个表在一个SQL查询中获取多个计数

时间:2017-04-14 00:47:49

标签: sql sql-server

我有2张桌子

公司&产品

我需要得到2个计数。一个是产品总数,第二个是销售产品数量_flg = 1

这个SQL似乎不起作用。还有其他几种方法......无法获得预期的结果

SELECT A.COMPANY_NAME, COUNT(B.PRODUCT_ID) AS TOTAL_COUNT_OF_PRODUCTS, 
       (CASE WHEN B.SALEFLG =1 THEN 1 END) AS COUNT_OF_SALES
FROM COMPANY A LEFT JOIN
     PRODUCT B
     ON B.COMPANY_ID = A.COMPANY_ID
GROUP BY A.COMPANY_NAME 

4 个答案:

答案 0 :(得分:1)

我认为你只需要case的总和:

SELECT C.COMPANY_NAME, COUNT(P.PRODUCT_ID) AS TOTAL_COUNT_OF_PRODUCTS, 
       SUM(CASE WHEN P.SALEFLG = 1 THEN 1 ELSE 0 END) AS COUNT_OF_SALES
FROM COMPANY C LEFT JOIN
     PRODUCT P
     ON P.COMPANY_ID = C.COMPANY_ID
GROUP BY C.COMPANY_NAME ;

答案 1 :(得分:0)

如果您有B.SALEFLG = 1或0,您可以尝试

deploy

或使用UNION

答案 2 :(得分:0)

如果你使用count然后在else中你应该考虑null,因为在计数聚合中不考虑null,如果你有B.SALEFLG = 1或0,那么使用sum聚合。

您可以尝试以下代码:

SELECT A.COMPANY_NAME, COUNT(B.PRODUCT_ID) AS TOTAL_COUNT_OF_PRODUCTS, 
       count(CASE WHEN B.SALEFLG =1 THEN 1 else null END) AS COUNT_OF_SALES
FROM COMPANY A LEFT JOIN
     PRODUCT B
     ON B.COMPANY_ID = A.COMPANY_ID
GROUP BY A.COMPANY_NAME

或试试这个:

SELECT A.COMPANY_NAME, COUNT(B.PRODUCT_ID) AS TOTAL_COUNT_OF_PRODUCTS, 
       sum(B.SALEFLG) AS COUNT_OF_SALES
FROM COMPANY A LEFT JOIN
     PRODUCT B
     ON B.COMPANY_ID = A.COMPANY_ID
GROUP BY A.COMPANY_NAME

答案 3 :(得分:0)

此SQL Server查询正在运行。 公司表和产品表 公司表CompanyID与产品表和sales_flg一起加入产品表。

sales_flg =在CntSalesflg中显示1条记录

select Comp.CompID as CompID, COUNT(Pro.ProductID) as CntProdustID, 
SUM(CASE WHEN Pro.SalesflagID = 1 THEN 1 ELSE 0 END) as CntSalesflg
from Product as Pro
inner join Company as Comp on Pro.CompID = Comp.CompID
GROUP by Comp.CompID