Sql Group By Two Fields

时间:2012-08-30 13:24:58

标签: sql pivot

我有两张表CustomersCustomerStatusEntries

CustomerStatusEntries
---------------------------
Id | Branch | CustomerStatus_Value | Customer_Id

CustomerStatus_Value  = ("B" = "Block" , "E" = "Created" etc...)

我需要获得此输出

enter image description here

3 个答案:

答案 0 :(得分:3)

SELECT Branch AS 'Branch Code',
    SUM(CASE WHEN CustomerStatus_Value = 'E' THEN 1 ELSE 0 END) AS 'Created',
    SUM(CASE WHEN CustomerStatus_Value = 'A' THEN 1 ELSE 0 END) AS 'Active',
    SUM(CASE WHEN CustomerStatus_Value = 'B' THEN 1 ELSE 0 END) AS 'Blocked',
    SUM(CASE WHEN CustomerStatus_Value = 'C' THEN 1 ELSE 0 END) AS 'Cancelled',
    COUNT(CustomerStatus_Value) AS 'All'
FROM CustomerStatusEntries
GROUP BY Id

答案 1 :(得分:1)

假设您在样本中显示了固定数量的列,您可以这样做:

SELECT Branch, 
       SUM(CASE WHEN CustomerStatus_Value = 'E' THEN 1 ELSE 0 END) AS Created,
       SUM(CASE WHEN CustomerStatus_Value = 'A' THEN 1 ELSE 0 END) AS Active,
       SUM(CASE WHEN CustomerStatus_Value = 'B' THEN 1 ELSE 0 END) AS Blocked,
       SUM(CASE WHEN CustomerStatus_Value = 'C' THEN 1 ELSE 0 END) AS Cancelled,
       COUNT(*) AS All
    FROM CustomerStatusEntries
    GROUP BY Branch;

答案 2 :(得分:1)

您可以使用标准SQL执行此操作:

select branch_code,
       sum(case when CustomerStatus_Value = 'E' then 1 else 0 end) as Created,
       sum(case when CustomerStatus_Value = 'B' then 1 else 0 end) as Blocked,
       ...
from t
group by branch_code
order by 1