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

时间:2015-01-09 14:24:42

标签: sql-server

我正在尝试根据服务类型ID获取提供商及其销售商品的数量。我想创建一个临时表,其中包含每个提供程序的每组服务类型中的项目数,但我只获得整个表的每个组的总计数。这是我到目前为止:

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

1 个答案:

答案 0 :(得分:2)

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

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