我创建了名为' group_test'的MariaDB(10.1.21)表。并保存了一些数据如下。
Group Item Value1 Value2 Value3
A a1 1 0 0
A a2 1 1 1
A a3 1 1 2
B b1 1 1 0
B b2 1 1 1
B b3 1 0 0
B b4 1 1 3
C c1 1 1 0
C c2 1 1 1
使用查询,我想立即生成如下结果。
Group Items Value1_1 Value2_1 Value3_1
A 3 3 2 1
B 4 4 3 1
C 2 2 2 1
项目是指'项目'的总数。在'组' ValueN_1表示' ValueN'的总数。 '组'中的值等于1。
我想我会使用GROUP BY和COUNT但我不确切知道该做什么 如何编写SQL以在一个查询中获得上述结果?
感谢。
答案 0 :(得分:1)
只需做一个GROUP BY
。由于Value1到Value3只有0和1,因此您可以使用SUM()
来计算1。
select Group, count(Item), sum(Value1), sum(Value2), sum(Value3)
from tablename
group by Group
修改“ ValueN的值可以是0到4 ”:
select Group,
count(Item),
sum(case when Value1 = 1 then 1 else 0 end) Value1_1,
sum(case when Value2 = 1 then 1 else 0 end) Value2_1,
sum(case when Value3 = 1 then 1 else 0 end) Value3_1
from tablename
group by Group
答案 1 :(得分:0)
假设value1
,value2
和value3
只能是0或1,您可以像这样写
select Group,
count(*) as Items,
sum(value1) as Value1_1,
sum(value2) as Value2_1,
sum(value3) as Value3_1
from yourTable t1
group by Group
如果情况并非如此,则必须使用case
sum
select Group,
count(*) as Items,
sum(case when value1 = 1 then 1 else 0 end) as Value1_1,
sum(case when value2 = 1 then 1 else 0 end) as Value2_1,
sum(case when value3 = 1 then 1 else 0 end) as Value3_1
from yourTable t1
group by Group
答案 2 :(得分:0)
在SELECT语句
中使用GROUP BY子句和SUM聚合函数SELECT *
FROM
(
SELECT [Group], count(Item) Item, sum(Value1) Value1, sum(Value2) Value2,
sum(Value3) Value3
FROM Your_tableName
GROUP BY [Group]
) A