1

我有两张桌子CustomersCustomerStatusEntries

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

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

我需要得到这个输出

在此处输入图像描述

4

3 回答 3

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
于 2012-08-30T13:31:48.637 回答
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;
于 2012-08-30T13:32:33.270 回答
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
于 2012-08-30T13:32:46.090 回答