我有一个简单的表格,记录在线广播电台的客户端连接。我试图根据整个时期的收听时间产生一个将返回前10个国家的视图,但按日期和日期分组。
澄清一下,前10名将是整个时期的前10名,而不仅仅是每一天。例如,美国可能是我们历史上第一的国家,但有些日子它可能下降到12,我仍然需要每天列出的前十大国家。
实际上,这应该产生一个视图,对于每一天,将有相同的十个国家,但总的收听时间。
我创建了一个返回所有国家/地区的视图:
SELECT DATE( datetime_end ) , country_code, SUM( duration ) /3600
FROM icecast_logs
WHERE mount = 'live'
GROUP BY DATE( datetime_end ) , country_code
答案 0 :(得分:1)
对于MSSQL使用TOP
SELECT TOP 10 DATE(datetime_end), country_code, SUM(duration)/3600
FROM icecast_logs
WHERE mount = 'live'
GROUP BY DATE(datetime_end), country_code
ORDER BY SUM(duration)/3600 DESC
对于MySQL使用LIMIT
SELECT DATE(datetime_end), country_code, SUM(duration)/3600
FROM icecast_logs
WHERE mount = 'live'
GROUP BY DATE(datetime_end), country_code
ORDER BY SUM(duration)/3600 DESC
LIMIT 10
对于Oracle,您需要使用RANK
& ROWNUM
WITH top_icecast_logs AS
(
SELECT DATE(datetime_end) AS Dateend, country_code, SUM(duration)/3600 AS SumTotalAmount,
RANK () OVER (ORDER BY SUM (SumtotalAmount) DESC) AS tsum
FROM icecast_logs
GROUP BY DATE(datetime_end), country_code
)
SELECT Dateend, country_code, SumTotalAmount
FROM top_icecast_logs
WHERE tsum <= 2
ORDER BY SumTotalAmount DESC;
答案 1 :(得分:0)
我设法通过使用INNER JOIN解决了这个问题:
SELECT DATE( datetime_end ) , icecast_logs.country_code, SUM( duration ) /3600 FROM icecast_logs
INNER JOIN
(SELECT country_code
FROM icecast_logs
WHERE mount = 'live'
GROUP BY country_code
ORDER BY SUM( duration ) DESC
LIMIT 10) AS TopTen
ON icecast_logs.country_code = TopTen.country_code
WHERE mount = 'live'
GROUP BY DATE( datetime_end ) , icecast_logs.country_code
答案 2 :(得分:0)
根据我的理解,您需要有史以来十大听众(此处:国家/地区)的每日统计数据。
首先,我们采用那些价值最高duration
的10个国家/地区代码,然后每天我们为这些国家/地区打印10个国家/地区的统计数据。
请记住,如果您没有10个国家/地区,则CTE将获取少于10行。此外,如果某个国家/地区在某些日子里没有收听,则不会显示在您的搜索结果中。这可以通过先生成日期然后将数据加入这些日期来处理,以便在每个日期显示每个国家/地区,并在0
duration_hrs
值
这应该会给你预期的结果。
WITH top_ten_all_time AS (
SELECT
country_code
FROM
icecast_logs
WHERE
mount = 'live'
GROUP BY country_code
ORDER BY SUM(duration) / 3600 DESC
FETCH FIRST 10 ROWS ONLY
)
SELECT
DATE(a.datetime_end) AS date_x,
a.country_code,
SUM(a.duration) / 3600 AS duration_hrs
FROM
icecast_logs a
INNER JOIN top_ten_all_time b USING (country_code)
WHERE
mount = 'live'
GROUP BY DATE(a.datetime_end), a.country_code
ORDER BY date_x, country_code