如何获得每行列组的不同计数?

How do I get a distinct count of column groups per row?

我正在尝试根据服务类型 ID 计算供应商数量和他们销售的商品。我想制作一个临时 table,其中包含每个提供者每组服务类型中的项目计数,但我只得到整个 table 中每个组的总数。这是我目前所拥有的:

SELECT dme_branches.provider_id, 
countDME= (select count(service_type_id) from dme_items where service_type_id
IN(1,2,3,5,6,11,12,13,14,15,19,20,21,22,24,25,29,31)), 

countOP=(select count(service_type_id) from dme_items where service_type_id IN (4,23)),

countHH=(select count(service_type_id) from dme_items where service_type_id IN (7,17,26,27)),

countDI=(select count(service_type_id) from dme_items where service_type_id IN (8,18,28)),

countTT=(select count(service_type_id) from dme_items where service_type_id IN (9,10)),

countIV=(select count(service_type_id) from dme_items where service_type_id IN (16)) 

INTO #branchClassification 
FROM dme_branches
JOIN dme_items ON dme_items.provider_id=dme_branches.provider_id
group by dme_branches.provider_id

您没有正确使用聚合函数。您的每个聚合列都是整个 table 的子查询,没有关于如何将其与当前行相关联的条件,因此这就是您获得相同结果的原因。 试试这个:

SELECT  dme_branches.provider_id, 
        countDME = SUM(CASE 
                            WHEN service_type_id IN (1,2,3,5,6,11,12,13,14,15,19,20,21,22,24,25,29,31)
                            THEN 1
                            ELSE 0 
                        END),
        countOP = SUM(CASE WHEN service_type_id IN (4,23) THEN 1 ELSE 0 END),
        countHH = SUM(CASE WHEN service_type_id IN (7,17,26,27) THEN 1 ELSE 0 END),
        countDI = SUM(CASE WHEN service_type_id IN (8,18,28) THEN 1 ELSE 0 END),
        countTT = SUM(CASE WHEN service_type_id IN (9,10) THEN 1 ELSE 0 END),
        countIV = SUM(CASE WHEN service_type_id = 16 THEN 1 ELSE 0 END),
INTO #branchClassification 
FROM dme_branches b
INNER JOIN dme_items i
    ON i.provider_id = b.provider_id
GROUP BY b.provider_id