SQL:每个字段值的计数输出表

时间:2012-07-31 06:42:48

标签: mysql sql sql-server oracle oracle10g

我们有以下数据。

TestName  Stage1  Stage2  Stage3  Stage4
Test1     John    Calra   John    Calre
Test2     Calra   null    John    Calra

我们需要实现一个以下面的格式显示数据的查询。

User    Stage1count  Stages2Count  Stages3count  Stages4Count
John         1             0             2             0
Calra        1             1             0             2

由于 约翰

2 个答案:

答案 0 :(得分:2)

您可以使用union来规范化数据。之后,常规pivot策略将起作用:

select  Name
,       sum(case when Stage = 1 then 1 end) as Stage1count
,       sum(case when Stage = 2 then 1 end) as Stage2count
,       sum(case when Stage = 3 then 1 end) as Stage3count
,       sum(case when Stage = 4 then 1 end) as Stage4count
from    (
        select  1 as Stage
        ,       Stage1 as Name
        from    YourTable
        union all
        select  2 as Stage
        ,       Stage2 as Name
        from    YourTable
        union all
        select  3 as Stage
        ,       Stage3 as Name
        from    YourTable
        union all
        select  4 as Stage
        ,       Stage4 as Name
        from    YourTable
        ) as SubQueryAlias
group by
        Name

答案 1 :(得分:0)

试试这个

 drop table tests
    CREATE TABLE tests(TestName varchar(10),Stage1 varchar(10),Stage2 varchar(10),Stage3 varchar(10),Stage4 varchar(10))
    INSERT INTO tests
    VALUES('Test1','John','Calra','John','Calra'),('Test2','Calra',null,'John','Calra')

select * from tests

    select 'John' as [User] 
          ,SUM(case when stage1='John' then 1 else 0 end) as stage1
          ,SUM(case when stage2='John' then 1 else 0 end) as stage2
          ,SUM(case when stage3='John' then 1 else 0 end) as stage3
          ,SUM(case when stage4='John' then 1 else 0 end) as stage4
    from tests 
    UNION 

    select 'Calra' as [User] 
          ,SUM(case when stage1='Calra' then 1 else 0 end) as stage1
          ,SUM(case when stage2='Calra' then 1 else 0 end) as stage2
          ,SUM(case when stage3='Calra' then 1 else 0 end) as stage3
          ,SUM(case when stage4='Calra' then 1 else 0 end) as stage4
    from tests