我有3张 table
- 设备1
+-------------+-------------+-------------+ | id_skt1 | status_kt1 | tgl_skt1 | +-------------+-------------+-------------+ | 1 | ON | 2019-07-23 | +-------------+-------------+-------------+ | 2 | ON | 2019-07-23 | +-------------+-------------+-------------+ | 3 | ON | 2019-07-24 | +-------------+-------------+-------------+
- equipment2
+-------------+-------------+-------------+ | id_skt2 | status_kt2 | tgl_skt2 | +-------------+-------------+-------------+ | 1 | ON | 2019-07-23 | +-------------+-------------+-------------+ | 2 | OFF | 2019-07-23 | +-------------+-------------+-------------+ | 3 | ON | 2019-07-25 | +-------------+-------------+-------------+
- equipment3
+-------------+-------------+-------------+ | id_skt3 | status_kt3 | tgl_skt3 | +-------------+-------------+-------------+ | 1 | OFF | 2019-07-25 | +-------------+-------------+-------------+ | 2 | ON | 2019-07-26 | +-------------+-------------+-------------+ | 3 | ON | 2019-07-26 | +-------------+-------------+-------------+ | 4 | ON | 2019-07-27 | +-------------+-------------+-------------+ | 5 | ON | 2019-07-27 | +-------------+-------------+-------------+ | 6 | ON | 2019-07-27 | +-------------+-------------+-------------+
how to count all status "ON" on these tables and group by date?
I have searched the website SO but i haven't found a similar problem
i've tried using this code:
SELECT (SELECT COUNT(*) FROM status_kt1 WHERE status_kt1="ON") as T1, (SELECT COUNT(*) FROM status_kt2 WHERE status_kt2="ON") as T2, (SELECT COUNT(*) FROM status_kt3 WHERE status_kt3="ON") as T3
I have searched the website so but did not find a similar problem I want the results like this: +-------------+-------------+ | tgl_all |totalStatusOn| +-------------+-------------+ | 2019-07-23 | 3 | +-------------+-------------+ | 2019-07-24 | 1 | +-------------+-------------+ | 2019-07-25 | 1 | +-------------+-------------+ | 2019-07-26 | 2 | +-------------+-------------+ | 2019-07-27 | 3 | +-------------+-------------+
问候 :)
最佳答案
连接所有表格并从结果中选择:
select tgl_all, count(tgl_all) as totalStatusOn from (
select status_kt1 as status, tgl_skt1 as tgl_all from equipment1
union all select status_kt2 as status, tgl_skt2 as tgl_all from equipment2
union all select status_kt3 as status, tgl_skt3 as tgl_all from equipment3) t
where status='ON' group by tgl_all;
tgl_all totalStatusOn
2019-07-23 3
2019-07-24 1
2019-07-25 1
2019-07-26 2
2019-07-27 3
顺便说一句,这似乎是一个糟糕的设计,如果你只有一张表,其中包含用于设备类型的附加字段,那会更好。
关于mysql - 按日期计算来自多个表和组的总数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57263991/