SQL 分组依据和计数函数

SQL Group By and Count function

我有以下数据库 table,我想按颜色计数和分组。我是 SQL 的一年级学生和初学者。谁能教我代码?

SQL-CountColor:

我尝试过的:

Select COLOR,
  sum(case when Blue = 1 then 1 else 0 end) as Blue_count,
  sum(case when Red then 1 else 0 end) as Red_count,
  sum(case when Yellow then 1 else 0 end) as Yellow_count,
  sum(case when Black then 1 else 0 end) as Black_count,
  sum(case when Green then 1 else 0 end) as Green_count,
from TAB_GROUP
group by COLOR;
select     sum(case when color = 'blue' then 1 else 0 end) as 'Blue',
           sum(case when color = 'red' then 1 else 0 end) as 'Red',
           sum(case when color = 'yellow' then 1 else 0 end) as 'Yellow',
           sum(case when color = 'Black' then 1 else 0 end) as 'Black',
           sum(case when color = 'Green' then 1 else 0 end) as 'Green'
From Table

你应该搜索一下,这是一个很常见的SQL语句。

select COLOR, count(*) from TAB_GROUP group by COLOR

你的问题基本正确。您需要做的就是删除 GROUP BY 并修复 case 以引用数据中的列:

select sum(case when color = 'Blue' then 1 else 0 end) as Blue_count,
       sum(case when color = 'Red' then 1 else 0 end) as Red_count,
       sum(case when color = 'Yellow' then 1 else 0 end) as Yellow_count,
       sum(case when color = 'Black' then 1 else 0 end) as Black_count,
       sum(case when color = 'Green' then 1 else 0 end) as Green_count
from TAB_GROUP;

您的查询存在的问题是您混合使用了两种方法,这两种方法都有效但不兼容。

第一个是使用 case 语句,就像@LONG 在其回答中所做的那样,它很好但不需要 group by;您已经 "artificially" 通过在每一列中给出不同的条件进行分组;

select  sum(case when Blue = 1 then 1 else 0 end) as Blue_count,
        sum(case when Red then 1 else 0 end) as Red_count,
        sum(case when Yellow then 1 else 0 end) as Yellow_count,
        sum(case when Black then 1 else 0 end) as Black_count,
        sum(case when Green then 1 else 0 end) as Green_count
from    TAB_GROUP

另一种方法是使用 group by,也可以,但您只需计算每个组的行数

select  COLOR, count(*) as CNT
from    TAB_GROUP
group by COLOR

这将为您提供与所需结果相同但行和列颠倒的结果

COLOR  | CNT 
Blue   | 2
Red    | 2
Yellow | 1
Black  | 1
Green  | 1

要将行移动到列,您需要一个旋转函数,其语法可能因您使用的数据库而异。这使得这种方法更加复杂,但在可能值的数量增加的情况下也更加通用。