在MySQL中将2和2个值分组在一起

在MySQL中将2和2个值分组在一起,mysql,group-by,Mysql,Group By,假设我们有一个问题 SELECT recordType,SUM(amount) FROM records GROUP BY recordType 输出 1: 50 2: 100 3: 150 4: 200 Group 1: 150 Group 2: 350 我们有4种不同的记录类型,分别是1、2、3和4。上述查询显然将返回为这4种类型分组的值。如何调整查询以显示基于成对分组的分组。Like在一行中返回recordType 1和recordType 2的结果,在第二行中返回recordTyp

假设我们有一个问题

SELECT recordType,SUM(amount) FROM records GROUP BY recordType
输出

1: 50
2: 100
3: 150
4: 200
Group 1: 150
Group 2: 350
我们有4种不同的记录类型,分别是1、2、3和4。上述查询显然将返回为这4种类型分组的值。如何调整查询以显示基于成对分组的分组。Like在一行中返回recordType 1和recordType 2的结果,在第二行中返回recordType 3和recordType 4的结果

预期产出

1: 50
2: 100
3: 150
4: 200
Group 1: 150
Group 2: 350
Like在一行中返回recordType 1和recordType 2的结果,在第二行中返回recordType 3和recordType 4的结果

你可以通过案例陈述来做到这一点。它不会表现得很好,但会起作用的。根据实际值,最终查询可能如下所示:

group by case
         when type in(1, 2) then 1
         when type in(3, 4) then 2
         when ...
         else ...
         end
Like在一行中返回recordType 1和recordType 2的结果,在第二行中返回recordType 3和recordType 4的结果

你可以通过案例陈述来做到这一点。它不会表现得很好,但会起作用的。根据实际值,最终查询可能如下所示:

group by case
         when type in(1, 2) then 1
         when type in(3, 4) then 2
         when ...
         else ...
         end

问题的一部分是正确分组,另一部分是获取组的名称

如果您确实有问题的数字,您可以:

select concat('Group ', cast((recordType - 1)/2 as int)), count(*)
from records r
group by cast((recordType - 1)/2 as int)
如果这些值在算术上不太合适,那么变量可能是最简单的方法:

select concat('Group ', @rn := @rn + 1), count(*)
from records r cross join (select @rn := 0) const
group by (case when type in (1, 2) then 1
               when type in (3, 4) then 2
          end)

问题的一部分是正确分组,另一部分是获取组的名称

如果您确实有问题的数字,您可以:

select concat('Group ', cast((recordType - 1)/2 as int)), count(*)
from records r
group by cast((recordType - 1)/2 as int)
如果这些值在算术上不太合适,那么变量可能是最简单的方法:

select concat('Group ', @rn := @rn + 1), count(*)
from records r cross join (select @rn := 0) const
group by (case when type in (1, 2) then 1
               when type in (3, 4) then 2
          end)