如何使用unpivot使这个存储过程更加优雅

时间:2014-08-11 09:11:27

标签: sql tsql stored-procedures pivot

我的数据采用以下格式:

ID          Category        Gender        Cost
1              C1             M            40
2              C2             F            50
3              C3             M            60
4              C1             F            40
5              C3             M            70
6              C3             F            50

。 。 。 等等

只有C1,C2和C3作为类别存在

我需要的结果是:

Category  Male %  Female %   Avg. Cost
   C1       0.5    0.5        40
   C2       0      1          50
   C3       0.6    0.4        60

我在存储过程中所做的是我声明的C1计数变量,C2计数和C3计数,C1女计数,C2女计数,C3女计数,C1总成本,C2总成本,C3总成本,你明白了。然后我计算了平均成本和男/女百分比。

它有效,但它不是一个非常优雅的解决方案。我无法让univot查询工作,因此它给了我需要的结果。这可以使用unpivot来完成,还是我误解了枢轴的工作原理?我尝试过类似下面的内容,但无法弄清楚如何包含每个类别的M / F百分比和平均成本。

感谢。

这样的东西(不完整):

Declare @TotalCount int;
SELECT @TotalCount = count(*) from MyTable;

SELECT Category, p.Total, CAST(p.Total * 1.0 / @TotalCount AS float) AS Percentage FROM --How to get F or M percentage, Average Cost Per Category , etc?
   (
        SELECT ISNULL(SUM(c.C1), 0) AS C1,
                      ISNULL(SUM(c.C2), 0) AS C2,
                      ISNULL(SUM(c.C3), 0) AS C3
               FROM
               (SELECT CASE WHEN Category = 'C1' THEN 1 ELSE 0 END AS C1,
                      CASE WHEN Category = 'C2' THEN 1 ELSE 0 END AS C2,
                      CASE WHEN Category = 'C3' THEN 1 ELSE 0 END AS C3
               FROM @Candidates
               ) c --Do I need
   ) a
   UNPIVOT
        (
               Total FOR Suitability IN (
                      C1,
                      C2,
                      C3
               )
        ) p

1 个答案:

答案 0 :(得分:1)

请查看以下查询:

select 
    Category,
    CAST(1.00*sum(case when Gender='M' then 1 else 0 end)/COUNT(Category) AS NUMERIC(18,1)) [Male %], 
    CAST(1.00*sum(case when Gender='F' then 1 else 0 end)/COUNT(Category) AS NUMERIC(18,1)) [Female %],  
    AVG(Cost) [Avg. Cost]
from tbl 
group by Category

SQL Fiddle Demo