我有一个 monitoring
表,其中包含客户端 ID 列 ID
,应用程序的上次登录日期 Time
。我编写了一个查询来显示表格,客户访问系统的时间如下:Time - Number of entries at this time - Client IDs。
要求:
select Time, count (*) as Quantity, group_concat (ClientID) from monitoring group by Time;
如何编写以下查询?以相同的形式显示表格,只是现在需要每次至少有1个客户端访问时,显示当时没有访问的所有客户端的id。
更新。
+---------------------+-------------+----------------+
| Time | Quantity | ClientID |
+---------------------+-------------+----------------+
| 2018-06-14 15:51:03 | 3 | 311,240,528 |
| 2018-06-14 15:51:20 | 3 | 314,312,519 |
| 2019-01-14 06:00:07 | 1 | 359 |
| 2019-08-21 14:30:04 | 1 | 269 |
+---------------------+-------------+----------------+
这些是当前具有访问权限的客户的 ID。并且您需要显示在特定时间没有访问权限的所有客户的 ID 也就是说,在这种情况下:
+---------------------+-------------+-----------------------------+
| Time | Quantity | ClientID |
+---------------------+-------------+-----------------------------+
| 2018-06-14 15:51:03 | 5 | 269,359,314,312,519 |
| 2018-06-14 15:51:20 | 5 | 311,240,528,359,269 |
| 2019-01-14 06:00:07 | 7 | 311,240,528,314,312,519,269 |
| 2019-08-21 14:30:04 | 7 | 311,240,528,314,312,519,359 |
+---------------------+-------------+-----------------------------+
建议不要考虑日期和时间,而只考虑年份和月份。但是一出来。谢谢。
最佳答案
您可以使用两个select distinct
子查询的cross join
生成所有可能的客户和时间组合,然后使用过滤掉表中存在的组合>不存在
。最后一步是聚合:
select t.time, count(*) as quantity, group_concat(c.clientid) as clientids
from (select distinct time from monitoring) t
cross join (select distinct clientid from monitoring) c
where not exists (
select 1
from monitoring m
where m.time = t.time and m.clientid = c.clientid
)
group by t.time
我不清楚问题中最后一句话的意思。上面的查询将生成您为示例数据显示的结果。
关于mysql - 在sql上写查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65207101/