我有4个表,其ID和日期。 如何在每个表中按日期计数不同的ID。 为了更好的解释:
第一张桌子:
1 | 01-11-2018
1 | 01-11-2018
3 | 03-11-2018
1 | 03-11-2018
第二张表:
1 | 01-11-2018
2 | 02-11-2018
3 | 03-11-2018
1 | 03-11-2018
以此类推。
结果我需要:
Date | Count first table | Count Second table|
01-11-2018 | 2 | 1
02-11-2018 | 0 | 2
03-11-2018 | 3 | 4
答案 0 :(得分:0)
一种方法是使用UNION ALL将全部唯一ID粘贴在一起。
然后对总计求和。
SELECT
`date` AS `Date`,
SUM(TotalUniqueId1) AS `Count First Table`,
SUM(TotalUniqueId2) AS `Count Second Table`,
SUM(TotalUniqueId3) AS `Count 3th Table`,
SUM(TotalUniqueId4) AS `Count 4th Table`
FROM
(
SELECT `date`,
COUNT(DISTINCT id) AS TotalUniqueId1,
0 AS TotalUniqueId2,
0 AS TotalUniqueId3,
0 AS TotalUniqueId4
FROM `Table1`
GROUP BY `date`
UNION ALL
SELECT `date`, 0, COUNT(DISTINCT id), 0, 0
FROM `Table2`
GROUP BY `date`
UNION ALL
SELECT `date`, 0, 0, COUNT(DISTINCT id), 0
FROM `Table3`
GROUP BY `date`
UNION ALL
SELECT `date`, 0, 0, 0, COUNT(DISTINCT id)
FROM `Table4`
GROUP BY `date`
) q
GROUP BY `date`
ORDER BY `date`;
答案 1 :(得分:0)
非常简单。您的数据库在那里存储和检索数据。不好格式化。你要做的是
select date, count(distinct id) from table1 group by date
然后,对第二个表执行相同的操作。
其余工作在应用程序层完成。