我有一个这样的表。
我想按时期(日期字段)进行选择 我可以返回登记册 和一列只匹配一列的登记册总数。
例如:如果我使用这个查询。
SELECT date, product_type, operation, unit
FROM table
WHERE date BETWEEN '2019-08-26 00:00:00' AND '2019-08-26 23:59:59';
它必须返回:
但我希望我可以多返回一列 不管是什么时期的操作总数,就像这样。
其中,6是 "ajoy "在表中出现的频率。
重要的是! 如果我选择了一个周期,其中有两个或更多的操作被返回,那么查询也必须能够返回它们的频率。
我使用了你的部分数据,并将包括我的数据在表中,但我相信这是你想要的东西
create table mytab (job int, operations char(8), prod char(8),
ts_date datetime year to minute, unit int) lock mode row;
insert into mytab values(22, "ajoy","arrow","2020-05-11 08:51", 20);
insert into mytab values(22, "ajoy","arrow","2020-05-11 08:51", 20);
insert into mytab values(22, "ajoy","arrow","2020-05-11 08:51", 20);
insert into mytab values(22, "ajoy","arrow","2020-04-11 14:15", 20);
insert into mytab values(22, "ajoy","arrow","2020-04-11 14:15", 20);
insert into mytab values(22, "ajoy","arrow","2020-04-11 14:15", 20);
insert into mytab values(23, "dinn","curve","2020-05-11 08:51",1);
insert into mytab values(23, "dinn","point","2020-05-11 08:51",1);
insert into mytab values(23, "dinn","arrow","2020-04-11 08:51",1);
的查询。
select job, operations, prod, ts_date, unit, (select count(*) from mytab b
where b.operations = a.operations) total_operation from mytab a where
a.ts_date between "2020-05-11 08:50" and "2020-05-11 08:59"
上面的查询给了我以下的结果 我想这就是你所要求的。
job operations prod ts_date unit total_operation
22 ajoy arrow 2020-05-11 08:51 20 6
22 ajoy arrow 2020-05-11 08:51 20 6
22 ajoy arrow 2020-05-11 08:51 20 6
23 dinn curve 2020-05-11 08:51 1 3
23 dinn point 2020-05-11 08:51 1 3
这个例子太小了,而且还没有考虑到索引的问题 你可以把索引放在表上,以加快查询速度