我有3张桌子
+-------------+-------------+-------------+ | id_skt1 | status_kt1 | tgl_skt1 | +-------------+-------------+-------------+ | 1 | ON | 2019-07-23 | +-------------+-------------+-------------+ | 2 | ON | 2019-07-23 | +-------------+-------------+-------------+ | 3 | ON | 2019-07-24 | +-------------+-------------+-------------+
+-------------+-------------+-------------+ | id_skt2 | status_kt2 | tgl_skt2 | +-------------+-------------+-------------+ | 1 | ON | 2019-07-23 | +-------------+-------------+-------------+ | 2 | OFF | 2019-07-23 | +-------------+-------------+-------------+ | 3 | ON | 2019-07-25 | +-------------+-------------+-------------+
+-------------+-------------+-------------+ | 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 | +-------------+-------------+-------------+
如何计算这些表上所有状态“ ON”并按日期分组?
我已经搜索过网站,但没有发现类似的问题
我尝试使用此代码:
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 | +-------------+-------------+
致谢:)
答案 0 :(得分:1)
连接所有表并从结果表中选择:
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
顺便说一句,这似乎是一个糟糕的设计,如果您只有一个表并带有用于设备种类的附加字段,那就更好了。