0

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.

1
  • SELECT country, ... GROUP BY title ... ??? really? If definite country value matches one and only one title value and backward then use GROUP BY country. If not then your query is obviously wrong and produces the output which makes no sense. Study ONLY_FULL_GROUP_BY SQL Mode. Commented Jan 29, 2022 at 18:39

2 Answers 2

1

Use the first as subquery for the second like

SELECT
   country
   SUM(viewz) as viewz
FROM (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 title) t1
GROUP BY country
ORDER BY viewz DESC;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much. This worked perfectly
0

if you are looking to use the SUM() function to sum-up all the viewz according to their country just use the following;

SELECT
     country
    ,SUM(d_view) AS viewz 
FROM mv_data
WHERE add_date BETWEEN '2022-01-26' AND '2022-01-26'
GROUP BY country
ORDER BY viewz DESC;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.