我具有以下数据库结构(数据不是真实的)
+------------+-------+-------------+
| Datum | Dauer | description |
+------------+-------+-------------+
| 11.01.2018 | 02:30 | Test |
| 11.02.2018 | 01:30 | Test |
| 11.02.2018 | 00:30 | Test |
| 11.03.2018 | 01:30 | Test |
| 11.03.2018 | 03:30 | Test |
| 11.03.2018 | 02:30 | Test |
| 11.04.2018 | 00:30 | Test |
| 11.04.2018 | 00:30 | Test |
| 11.05.2018 | 01:30 | Test |
| 11.05.2018 | 01:00 | Test |
| 11.05.2018 | 01:30 | Test |
| 11.06.2018 | 00:30 | Test |
| 11.06.2018 | 00:30 | Test |
| 11.06.2018 | 02:30 | Test |
| 11.06.2018 | 01:30 | Test |
| 11.07.2018 | 01:30 | Test |
| 11.07.2018 | 00:30 | Test |
| 11.07.2018 | 03:30 | Test |
| 11.08.2018 | 05:30 | Test |
| 11.08.2018 | 00:30 | Test |
| 11.08.2018 | 00:30 | Test |
| 11.08.2018 | 01:30 | Test |
| 11.08.2018 | 02:30 | Test |
| 11.08.2018 | 00:30 | Test |
| 11.09.2018 | 01:30 | Test |
| 11.09.2018 | 02:30 | Test |
| 11.09.2018 | 01:30 | Test |
+------------+-------+-------------+
我想创建一个查询来获取每个月的前10个值,并按月和时间排序。
我尝试了以下查询
SELECT Top 10 *
FROM History_query where Month(Datum)=1 and Dauer >= #01:00# order by Dauer desc
Union
SELECT Top 10 *
FROM History_query where Month(Datum)=2 and Dauer >= #01:00# order by Dauer desc
问题是我必须为每个月和2019年写12次工会查询。
有另一种方法可以使它更简单。
非常感谢您的帮助。
答案 0 :(得分:0)
您可以使用子查询:
SELECT *
FROM History_query
WHERE Dauer IN
(SELECT Top 10 Dauer
FROM History_query As T
WHERE Year(T.Datum) = Year(History_query.Datum)
AND Month(T.Datum) = Month(History_query.Datum)
AND T.Dauer >= #01:00#
ORDER BY Dauer desc)
修改:
您可以尝试使用辅助查询:
SELECT
Year([Datum]) * 100 + Month([Datum]) As YearMonth,
Dauer
FROM
History_query
WHERE
Dauer >= #01:00#
将其另存为 YMHistory 。然后在最终查询中使用它:
SELECT *
FROM YMHistory
WHERE Dauer IN
(SELECT Top 10 Dauer
FROM YMHistory As T
WHERE T.YearMonth = YMHistory.YearMonth
ORDER BY Dauer desc)