如何按行对项目进行分组

How to group items by rows

我想对商店数量进行分组,但我不确定创建 table 中不存在的组的语法是什么。我希望输出是这样的

Group | Number of items
  1   |    XXX
  2   |    XXX

组 1 的项目数少于 10,而组 2 的项目数多于 10.I 具有项目数的数据,但我需要创建组号和我不确定如何。提前谢谢你。

我试过的方法:

SELECT 
case when b.item_stock < 10 then count(a.shopid) else null end as Group_1,
case when b.item_stock >= 10 or b.item_stock < 100 then count(a.shopid) else null end as Group_2


FROM `table_a` a
left join `table_b` b
on a.id= b.id

where registration_time between "2017-01-01" and "2017-05-31"

group by b.item_stock

LIMIT 1000

从您分享的示例来看,您已经接近解决这个问题,只需要调整您的案例陈述。

您查询中的 case 语句将组拆分为两个单独的列,而您需要将这些组放在一列中,并在右侧显示总计。

考虑对您的 select 语句进行以下更改。

case when b.item_stock < 10 then "Group_1"
when b.item_stock >= 10 then "Group_2" else null end as Groups,
count(a.shop_id) as total

架构 (MySQL v5.7)

CREATE TABLE id (
  `shop_id` VARCHAR(5),
  `item_stock` INTEGER
);

INSERT INTO id
  (`shop_id`, `item_stock`)
VALUES
  ('ID001', '40'),
  ('ID002', '20'),
  ('ID003', '30'),
  ('ID004', '9'),
  ('ID005', '44'),
  ('ID006', '22'),
  ('ID007', '28'),
  ('ID008', '35'),
  ('ID009', '20'),
  ('ID010', '4'),
  ('ID011', '5'),
  ('ID012', '45'),
  ('ID013', '29'),
  ('ID014', '8'),
  ('ID015', '40'),
  ('ID016', '26'),
  ('ID017', '31'),
  ('ID018', '48'),
  ('ID019', '45'),
  ('ID020', '13');

查询#1

SELECT 
case when item_stock < 10 then "Group_1"
when item_stock >= 10 then "Group_2" else null end as Groups,
count(shop_id) as total
FROM id group by 1;
Groups total
Group_1 4
Group_2 16

View on DB Fiddle

汤姆

下面是执行此操作的 BigQuery 方法

select 'group_' || range_bucket(item_stock, [0, 10]) as group_id,
  count(*) as number_of_items
from your_table 
group by group_id          

如果应用于像

这样的虚拟数据
with your_table as (
  select 'ID001' shop_id, 40 item_stock union all
  select 'ID002', 20 union all
  select 'ID003', 30 union all
  select 'ID004', 9 union all
  select 'ID005', 44 union all
  select 'ID006', 22 union all
  select 'ID007', 28 union all
  select 'ID008', 35 union all
  select 'ID009', 20 union all
  select 'ID010', 4 union all
  select 'ID011', 5 union all
  select 'ID012', 45 union all
  select 'ID013', 29 union all
  select 'ID014', 8 union all
  select 'ID015', 40 union all
  select 'ID016', 26 union all
  select 'ID017', 31 union all
  select 'ID018', 48 union all
  select 'ID019', 45 union all
  select 'ID020', 13 
)          

输出是

这个解决方案的好处是它很容易扩展到任意数量的范围,只需将它们添加到 range_bucket 函数中 -
例如:range_bucket(item_stock, [0, 10, 50, 100, 1000])