有关计算SQL中两个表的唯一字段组合的问题。 MSaccess 2003。
table1: id, fld1, fld2
table2: id, dateAndTime
id不是唯一的;表格在“id”之间加入。
我需要按fld1
和fld2
(int)的不同组合按日期(dd / mm / yy - 忽略时间)进行计数。
更具体地说,我需要知道哪个日期具有fld1
和fld2
的最独特组合。
如果table1有
1, 101, 101 2, 101, 101 3, 101, 101 4, 101, 102 5, 101, 102 6, 101, 103
表2有
1, 12/1/2010 2, 12/1/2010 3, 12/1/2010 1, 12/2/2010 2, 12/2/2010 4, 12/2/2010 5, 12/2/2010 6, 12/2/2010
我需要
12/1/2010, 1 'only 1 unique combinatin of fld1 and fld2
12/2/2010, 3 'only 3 unique combinations of fld1 and fld2
但我只需要“12/2/2010,3”输出,因为我只需要最大计数的日期和计数。
无法弄清楚如何在Commment中将其格式化为下面的正确答案 - 所以这里是MS Access 2003。
Select TOP 5 theDay, count(*) AS theCount
FROM (
Select cdate(int(date_col)) As theDay
From tbl1 Inner Join tbl2 on tbl1.id=tbl2.id
Group By cdate(int(date_col)), fld1, fld2
) As X
Group By theDay
Order By 2 Desc;
按日期返回TOP 5组合(忽略任何时间值)
答案 0 :(得分:0)
在现代RDBMS中,您可以一次性计算不同的组合:
SELECT date_col, count(DISTINCT (fld1, fld2)) AS unique_combos
FROM tbl1
JOIN tbl2 USING (id)
GROUP BY date_col;
如果不起作用,则分两步执行简单方法:
SELECT date_col, count(*) AS unique_combos
FROM (
SELECT date_col
FROM tbl1
JOIN tbl2 ON tbl1.id = tbl2.id
GROUP BY date_col, fld1, fld2
) AS x
GROUP BY date_col;
第二个也应该在MS Access中工作。
最终@ user2184214的用途:
SELECT TOP 5 theDay, count(*) AS theCount
FROM (
SELECT cdate(int(date_col)) AS theDay
FROM tbl1
JOIN tbl2 ON tbl1.id = tbl2.id
GROUP BY cdate(int(date_col)), fld1, fld2
) AS x
GROUP BY theDay
ORDER BY 2 DESC;
答案 1 :(得分:0)
此查询为您提供所需内容:
SELECT
date(dateAndTime) AS date,
count(DISTINCT (fld1, fld2)) AS count
FROM table1
JOIN table2 ON table1.id = table2.id
GROUP BY 1
HAVING count(DISTINCT fld1, fld2) > 1
ORDER BY 2 DESC