【问题标题】:SQL Count Query with GroupBy使用 GroupBy 的 SQL 计数查询
【发布时间】:2014-07-19 22:34:31
【问题描述】:

我在表格中有以下格式的数据

ID CSLang VBLang Level Occurrence
1  FALSE  TRUE   1 - 4  1
2  FALSE  TRUE   5 - 9  1
3  FALSE  TRUE   0 - 0  1
4  TRUE   FALSE  1 - 4  1
5  TRUE   FALSE  5 - 9  1
6  TRUE   FALSE  10 - 15 1
7  TRUE   TRUE   0 - 0  1
8  FALSE  FALSE  0 - 0  1


我想获得如下数据(我想要真正按级别分组的 CSharp 和 VB 的计数)

Level CountCS CountVB       
0 - 0   1       2       
1 - 4   1       1       
5 - 9   1       1       
10 - 15 1       0

【问题讨论】:

    标签: sql-server select pivot


    【解决方案1】:

    您可以尝试如下(假设您使用的是 MySQL)。查看演示小提琴http://sqlfiddle.com/#!2/08b00f/4

    select level,
    sum(CSharpLang = 'true') as CountCSharp,
    sum(VBLang = 'true') as CountVBLang     
    from table1
    group by level
    order by level
    

    每次更新,如果您使用的是SQL Server,那么您可以执行以下操作。一个演示小提琴http://sqlfiddle.com/#!3/7fa05/3

    select level,
    sum(case when CSLang = 'true' then 1 else 0 end) as CountCSharp,
    sum(case when VBLang = 'true' then 1 else 0 end) as CountVBLang     
    from table1
    group by level
    order by level
    

    【讨论】:

    • 您的回答给了我解决方案,当我使用以下解决方案时,它起作用了
    • 选择 NumOfConditionalBPs,Sum(当 ScriptEngine_7 = 'False' Then 1 else 0 End)作为脚本,Sum(当 ManagedOnlyEngine_5 = 'False' Then 1 else 0 End)作为由 DbgEngines Group By 管理NumOfConditionalBPs 按 NumOfConditionalBPs 排序
    • 如果您运行小提琴链接,则解决方案似乎是正确的。为什么投反对票?
    • @BoratSagdiyev,您遇到了语法错误,原因是您在 SQLServer 中尝试过。语法有一点不同。立即检查编辑。
    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    相关资源
    最近更新 更多