I have a SQL statement that returns some records depending on some given variables.
Query:
SELECT
country
,(MAX(d_views) - MIN(d_views)) AS viewz
FROM mv_data
WHERE add_date BETWEEN '2022-01-22' AND '2022-01-22'
GROUP BY title
ORDER BY viewz DESC;
Output:
| country | viewz |
|---|---|
| NG | 14735 |
| NG | 12494 |
| GH | 6099 |
| GH | 5181 |
| GH | 3381 |
| NG | 3293 |
| GH | 2288 |
| NG | 169 |
What I'm looking for is:
To use the SUM() function to sum up all the viewz according to their country, something like:
| country | viewz |
|---|---|
| NG | 30691 |
| GH | 16949 |
And this is what I did:
SELECT
country
,SUM(MAX(d_views) - MIN(d_views)) AS viewz
FROM mv_data
WHERE add_date BETWEEN '2022-01-26' AND '2022-01-26'
GROUP BY title
ORDER BY viewz DESC;
But I'm getting this error:
#1111 - Invalid use of group function
I also tried to GROUP BY country without the SUM() function and the result is incorrect:
Query:
SELECT
country
,(MAX(d_views) - MIN(d_views)) AS viewz
FROM mv_data
WHERE add_date BETWEEN '2022-01-26' AND '2022-01-26'
GROUP BY country
ORDER BY viewz DESC;
Output:
| country | viewz |
|---|---|
| NG | 4918377 |
| GH | 8185474 |
What I am doing wrong?
NB: d_views is a field in my table. Depending on a given date, we have a minimum value and a maximum value.
SELECT country, ... GROUP BY title ...??? really? If definitecountryvalue matches one and only onetitlevalue and backward then useGROUP BY country. If not then your query is obviously wrong and produces the output which makes no sense. StudyONLY_FULL_GROUP_BYSQL Mode.