简体   繁体   English

计算SQL Server中的每个不同值

[英]Get count against each distinct value in SQL Server

I have a table tbl_demo like this: 我有一个像这样的表tbl_demo

              aliasname is_correct
                    10  INCORRECT
                    10  INCORRECT
                    10  INCORRECT
                    10  CORRECT
                    10  CORRECT
                    10  NOT SOLVED
                    9   INCORRECT
                    9   INCORRECT
                    9   CORRECT

I created a query: 我创建了一个查询:

select 
    aliasname, 
    count(*) as quest_count,  
    is_correct 
from 
    tbl_demo 
group by 
    aliasname, is_correct order by aliasname

and I get output like this 我得到这样的输出

              aliasname quest_count  is_correct
              ---------------------------------
              10          2            CORRECT
              10          3            INCORRECT
              10          1            NOT SOLVED
               9          1            CORRECT
               9          2            INCORRECT

but I want 0 for in 9 and NOT solved 但我希望在9中0,而不是解决

Like one more row like this 就像这样的一行

                9         0            NOT SOLVED

Can this be achieved easily, and how? 这可以轻松实现,以及如何实现?

You can do this by generating all possible combinations using cross join , and the using left join to bring in the original data. 您可以通过使用cross join生成所有可能的组合,并使用left join来引入原始数据。 The rest is just aggregation: 其余的只是聚合:

select a.aliasname, count(d.aliasname) as quest_count, ic.is_correct
from (select distinct aliasname from tbl_demo
     ) a cross join
     (select distinct is_correct from tbl_demo
     ) ic left outer join
     tbl_demo d
     on d.aliasname = a.aliasname and d.is_correct = ic.is_correct
group by a.aliasname, ic.is_correct;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM