如何在时间查询中进行左连接

How can I make a left join in a temporal query

我有以下 table:

char, id_1, id_2
a,100,50
a,100,50
a,100,50
b,101,50
b,101,50
c,200,51
c,200,51
d,201,51
e,202,52
e,202,52
e,202,52
e,202,52

我想产生这个输出:

id_1, id_2, count, sum
100,50,3,5
101,50,2,5
200,51,2,3
201,51,1,3
202,52,4,4

简短说明:

我想计算给定“id_1”的行数并生成列“count” 然后一旦我有了“计数”列,我想通过对组求和来创建“总和”列 id_2

我先试试这个:

select id_1, id_2, count(id_2) as count from myTable
group by id_1, id_2

制作计数列,

id_1, id_2, count
100,50,3
101,50,2
200,51,2
201,51,1
202,52,4

问题是我无法创建总和列。

你有什么想法吗?提前致谢。

如果您使用的是 MySql 8+,那么 window 函数 让这变得相对简单:

select id_1, id_2, Count(*) "Count", Max(cnt) "sum"
from (
    select *, Count(*) over(partition by id_2) cnt
    from t
)t
group by id_1, id_2;

See demo Fiddle

正如 Stu 所说,window 函数使这项任务变得轻而易举。这是我对这项任务的看法(当我完成时,Stu 已经回复了,无论如何也可以分享我的)。

架构 (MySQL v8.0)

CREATE TABLE Test (
  `id_1` INTEGER,
  `id_2` INTEGER
);

INSERT INTO Test
  (`id_1`, `id_2`)
VALUES
  ('100', '50'),
  ('100', '50'),
  ('100', '50'),
  ('101', '50'),
  ('101', '50'),
  ('200', '51'),
  ('200', '51'),
  ('201', '51'),
  ('202', '52'),
  ('202', '52'),
  ('202', '52'),
  ('202', '52');

查询#1

select distinct 
*,
count(id_1) over (partition by id_1) as count,
count(id_2) over (partition by id_2) as sum
from Test;
id_1 id_2 count sum
100 50 3 5
101 50 2 5
200 51 2 3
201 51 1 3
202 52 4 4

View on DB Fiddle