【问题标题】:SQL: output table of counts per field valueSQL:输出每个字段值的计数表
【发布时间】:2012-07-28 21:20:29
【问题描述】:

我们有以下数据。

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

谢谢 约翰

【问题讨论】:

  • 使用子查询。但没有成功。
  • 嗨,约翰。你没有指定一个问题。此外,您的帖子没有显示任何解决问题的尝试,并且看起来您希望其他人为您完成工作。您能否编辑您的问题,让我们了解您尝试过的方法和不适合您的方法?有在FAQ 中发布好问题的提示。

标签: mysql sql sql-server oracle oracle10g


【解决方案1】:

您可以使用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

【讨论】:

    【解决方案2】:

    试试这个

     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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多