我有以下数据库表,我想按颜色计算和分组。我是一年级学生,也是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;
答案 0 :(得分:1)
你应该搜索一下,这是一个非常常见的SQL语句。
select COLOR, count(*) from TAB_GROUP group by COLOR
答案 1 :(得分:0)
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
答案 2 :(得分:0)
您的查询基本正确。您只需删除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;
答案 3 :(得分:0)
您的查询存在的问题是您正在混合两种方法,这两种方法都有效但不兼容。
第一个是使用case
语句,就像@LONG在答案中所做的那样,它很好,但并不需要group by
;你已经"人为地"通过在每列中给出不同的条件进行分组;
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
要将行移动到列,您需要一个旋转功能,其语法可能会因您使用的数据库而异。这使得这种方法更加复杂,但在可能的数量增加的情况下也更加通用。