您好我有两个不同的表,具有相同的字段created_date
(日期时间)
现在我想要记录哪些日历记录与连接表我已经为个人计数做了如下查询:
SELECT DATE(created_date), COUNT(*) FROM table1 GROUP BY DAY(created_date)
SELECT DATE(created_date), COUNT(*) FROM table2 GROUP BY DAY(created_date)
我正在为这样的人获得结果:
结果我需要:
DATE(created_date) count(table1) count(table2)
2016-12-01 10 3
2016-12-02 1 0
2016-12-05 1 0
2016-11-29 1 0
2016-11-30 4 1
现在我只想加入这些结果,根据桌面的个人观看次数,任何人都可以帮我解决这个问题....
答案 0 :(得分:3)
首先在两个表之间取一个UNION
,然后使用条件聚合来确定两个表中每个表的计数。请注意,我引入了一个名为table_name
的字段来跟踪两个表中每个表的数据。
SELECT t.created_date,
SUM(CASE WHEN t.table_name = 'one' THEN 1 ELSE 0 END) AS count_table_one,
SUM(CASE WHEN t.table_name = 'two' THEN 1 ELSE 0 END) AS count_table_two
FROM
(
SELECT DATE(created_date) AS created_date, 'one' AS table_name
FROM table1
UNION ALL
SELECT DATE(created_date), 'two'
FROM table2
) t
GROUP BY t.created_date
我始终如一地使用DATE
来使查询正确。
答案 1 :(得分:1)
您的查询存在问题,您按DAY(日期)进行分组并显示' date'所以结果将是第一天与日期(日期),但重复它以避免误解:)
select IFNULL(A.cd, B.cd), A.cnt, B.cnt from
(SELECT DAY(created_date) d, DATE(created_date) cd, COUNT(*) cnt
FROM table1 GROUP BY DAY(created_date)) as A
LEFT JOIN
(SELECT DAY(created_date) d, DATE(created_date) cd , COUNT(*) cnt
FROM table2 GROUP BY DAY(created_date)) B ON B.d = A.d
答案 2 :(得分:1)
试试这个:
SELECT created_date, sum(countTable1) countTable1,
sum(countTable2) countTable2
FROM (
SELECT DATE(created_date) created_date, COUNT(*) countTable1, NULL countTable2
FROM table1 GROUP BY DAY(created_date)
UNION ALL
SELECT DATE(created_date) created_date, NULL, COUNT(*) countTable2
FROM table2 GROUP BY DAY(created_date)) t GROUP BY t.created_date
答案 3 :(得分:0)
如果不需要允许重复行,则使用union
并不是太难用其他行使用union all
(意味着也允许重复)。
SELECT DATE(created_date), COUNT(*) FROM table1 GROUP BY DAY(created_date)
UNION
SELECT DATE(created_date), COUNT(*) FROM table2 GROUP BY DAY(created_date)
答案 4 :(得分:0)
SELECT T.create_date,ISNULL(T.count,0)AS Counttable1,ISNULL(X.count,0)AS Counttable2 FROM(SELECT DATE(created_date) AS create_date,COUNT(*) as count FROM table1 GROUP BY DAY(created_date)) AS T LEFTJOIN(SELECT DATE(created_date) AS create_date, COUNT(*) as count FROM table2 GROUP BY DAY(created_date))AS X ON T.create_date=X.create_date
答案 5 :(得分:0)
你实际上需要一个SQL UNION。加入自然消除计数,因为maytch字段。即如果您在table1
和table2
中都有2016-12-01,那么JOIN
上的created_date
会给您1而不是2的计数。
SELECT DATE(total.created_date), COUNT(*)
FROM (
SELECT created_date FROM table1
UNION ALL
SELECT created_date FROM table2) as total
GROUP BY total.created_date
在这里,您只需将两个表联合起来,因为它们具有匹配的列名。然后你从两个表中找回每个日期。那是在内部查询中。然后外部查询进行计数。
希望这是有道理的。