根据日期和 ID 计算每年和每月的记录

Count records per year and month based on date & id

我有以下 table.

date       location_id    type_id   other_id   
01/01/2021       1           22       3         
01/01/2021       1           22       5         
01/01/2021       2            1       1         
15/01/2021       2            1       1         
22/01/2021       1           22       1         
01/02/2021       1            1       1   
01/02/2021       1           22       1  

我想根据 location_id 和 type_id 计算每个 year/month 的记录数。 我想要的输出应该是这样的:

date       location_id    type_id   other_id   count
01/01/2021       1           22       3         3
01/01/2021       1           22       5         3
01/01/2021       2            1       1         2
15/01/2021       2            1       1         2
22/01/2021       1           22       1         3
01/02/2021       1            1       1         1
01/02/2021       1           22       1         1

我尝试过的:

select year(day_dt), month(day_dt), location_id, type_id count(1) as nb_record
from preliminar 
group by year(day_dt), month(day_dt), location_id, type_id

但是这个查询的问题是,我没有得到 table 中每个初始行的计数,而且我丢失了当天的信息。

如有任何帮助,我们将不胜感激

数据 使用 MySQL/HiveQL

CREATE TABLE preliminar (
  day_dt date NOT NULL,
  location_id int,
  type_id int,
  other_id int);

INSERT INTO preliminar 
    (day_dt, location_id,type_id, other_id) 
VALUES 
    ('2021-01-01',1, 22, 3),
    ('2021-01-01',1, 22, 5),
    ('2021-01-01',2,  1, 1),
    ('2021-01-15',2,  1, 1),
    ('2021-01-22',1,  22, 1),
    ('2021-02-01',1,  1, 1),
    ('2021-02-01',1,  22, 1);

使用 MySQL 8.0 window 函数

SELECT *, COUNT(*) OVER(PARTITION BY location_id, type_id, YEAR(day_dt), MONTH(day_dt)) counts
FROM preliminar
ORDER BY day_dt

db<>fiddle