MYSQL - 如何 select with group by 和 having

MYSQL - how to select with group by and having

我有这个架构:

table = users
user_id - integer
user_name - string

table = transaction
transaction_id - string
user_id - integer

此示例数据:

user_id -  user_name
2       -  Jhon
3.      -  barry

transaction_id - user_id
19123          -  2
20123          -  2
20124          -  2
21123          -  2 

我只需要获取用户 jhon 在 19 和 20 进行了多少次交易 transaction_id 的前 2 位数字是年份,但我似乎无法将它们分组,我有的是:

select u.user_name
from transaction t join users u on u.user_id = t.user_id
group by (substr(t.transaction_id, 1, 2))
where <I have no idea in how to fill this>

我想要的结果是:

jhon 1 2

19 年有 1 笔交易 20

中有 2 笔交易

日期最好保存在mysql方式2022-12-31,所以你cqan使用带输入转换的日期函数。

您需要按姓名和前 2 位数字分组

并且 WHERE 子句始终位于分组依据

之前
CREATE TABLE users (
  `user_id` INTEGER,
  `user_name` VARCHAR(5)
);

INSERT INTO users
  (`user_id`, `user_name`)
VALUES
  ('2', 'Jhon'),
  ('3.', 'barry');
CREATE TABLE transaction (
  `transaction_id` INTEGER,
  `user_id` INTEGER
);

INSERT INTO transaction
  (`transaction_id`, `user_id`)
VALUES
  ('19123', '2'),
  ('20123', '2'),
  ('20124', '2'),
  ('21123', '2');
select u.user_name, Count(*)
from transaction t join users u on u.user_id = t.user_id
where u.user_name = 'Jhon' AND (substr(t.transaction_id, 1, 2)) IN  (19,20)
group by u.user_name,(substr(t.transaction_id, 1, 2))
user_name | Count(*)
:-------- | -------:
Jhon      |        1
Jhon      |        2
select u.user_name
, SUM((substr(t.transaction_id, 1, 2)) = 19) As `Count_19`
, SUM((substr(t.transaction_id, 1, 2)) = 20) As `Count_20`
from transaction t join users u on u.user_id = t.user_id
where u.user_name = 'Jhon' AND (substr(t.transaction_id, 1, 2)) IN  (19,20)
group by u.user_name
user_name | Count_19 | Count_20
:-------- | -------: | -------:
Jhon      |        1 |        2

db<>fiddle here