[英]SQL MAX and total of by date and product
需要幫助 - 我需要從表格中獲得所有日子中每天貢獻最多的頁面的百分比。 我需要按日期、頁面、占該日期總訂閱量的百分比、占總時間的百分比來顯示它
這是表:
P_date | PageName | Subscribes
02/05/2020 page1 258
05/05/2020 page1 10
01/07/2020 page1 236
02/05/2020 page2 15
02/05/2020 page3 14
05/05/2020 page2 13
05/05/2020 page3 223
這是我的代碼:
select P_date,
max(total_subs) as Max_subs,
format((max(total_subs)/sum(total_subs)),'.00%') as 'Percentage out of total that day',
format((max(total_subs) / (select sum(total_subs) from
table1)),'.00%') as 'Percentage out of total' from table1
group by P_date order by 'Percentage out of total' desc
輸出是:
但我還需要添加頁面名稱 - 我需要每天顯示 1 個最佳頁面?
在 MSSQL 中,您可以執行以下操作:
SELECT * /*specify desired columns here*/
(
SELECT * FROM (
SELECT table1.*, ROW_NUMBER() OVER(PARTITION BY P_date ORDER BY Subscribes DESC) as row_num
FROM table1 )
WHERE row_num = 1
) as bestPagePerDate
JOIN (
select P_date,
max(total_subs) as Max_subs,
format((max(total_subs)/sum(total_subs)),'.00%') as 'Percentage out of total that day',
format((max(total_subs) / (select sum(total_subs) from
table1)),'.00%') as 'Percentage out of total' from table1
group by P_date order by 'Percentage out of total' desc
) as yourQuery
ON yourQuery.P_date = bestPagePerDate.P_date
您可以按如下方式使用窗口函數:
select p_date, page_name, total_subs, 1
1.0 * total_subs / total_subs percentage_day,
1.0 * total_subs / sum_total_subs percentage_overall
from (
select t.*,
row_number() over(partition by p_date order by total_subs desc) rn
sum(total_subs) over(partition by p_date) p_date_total_subs,
sum(total_subs) over() overal_total_subs
from table1 t
) t
where rn = 1
您可以使用每天最佳頁面的查詢進行子查詢,並將其顯示在您的全局查詢中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.