简体   繁体   中英

How to count a field per day and then GROUP BY YEARWEEK

If i have a database with 2 columns, date and account and i want to first count account per day and then group by week. How wrong is my code and how to do it? I edited my code a little bit, i was not thinking right from the beginning. I want the sum to be 9 for week 48.

SELECT date, account,
(SELECT date, COUNT(DISTINCT account) 
FROM t1 
GROUP BY date
) AS sum

FROM t1
GROUP BY YEARWEEK(date) 

在此处输入图片说明

You seem to be looking for a simple aggregate query with count(distinct ...) :

select yearweek(date) year_week, count(distinct account) cnt_account
from t1
group by yearweek(date)
order by year_week

Note: yearweek() gives you the year and week; this is better than week() , if your data spreads over several years.

EDIT

From the comments, you need two levels of aggregation:

select yearweek(dy) year_week, sum(cnt) cnt_account
from (
    select date(t1.date) dy, count(distinct t1.account) cnt
    from t1
    group by date(t1.date)
) t
group by yearweek(dy)
order by year_week

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM