Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two select queries in one

Tags:

sql

oracle

I have three tables : history, video and user. The two following queries display for each video the number of views for french users or for german users :

SELECT V.idVideo, COUNT(H.idVideo) AS nb_fr
FROM HISTORY H
INNER JOIN VIDEO V ON V.idVideo = H.idVideo
INNER JOIN USER U ON U.idUser = H.idUser
WHERE U.nationality = 'french'
GROUP BY H.idVideo
ORDER BY V.idVideo;

and

SELECT V.idVideo, COUNT(H.idVideo) AS nb_ge
FROM HISTORY H
INNER JOIN VIDEO V ON V.idVideo = H.idVideo
INNER JOIN USER U ON U.idUser = H.idUser
WHERE U.nationality = 'german'
GROUP BY H.idVideo
ORDER BY V.idVideo

But how combine this two queries to have only one ? I would like something like that :

idVideo | nb_fr | nb_ge
-----------------------
    1   |   5   |   4
    2   |   3   |   6
    3   |   2   |   8
    4   |   3   |   3
like image 610
iAmoric Avatar asked Oct 26 '16 11:10

iAmoric


People also ask

How do I combine two SQL queries in one result without a UNION?

You need to create two separate queries and join their result not JOIN their tables. Show activity on this post. JOIN and UNION are differents. In your query you have used a CROSS JOIN operation, because when you use a comma between two table you apply a CROSS JOIN.

Can you run 2 queries in SQL?

You can include multiple SQL statements on the SQL query panel. The exceptions are CALL and CREATE PROCEDURE statements. These statements must be used alone in a query.


2 Answers

Use case expressions to do conditional aggregation:

SELECT V.idVideo,
       COUNT(case when U.nationality = 'french' then H.idVideo end) AS nb_fr,
       COUNT(case when U.nationality = 'german' then H.idVideo end) AS nb_ge
FROM HISTORY H
INNER JOIN VIDEO V ON V.idVideo = H.idVideo
INNER JOIN USER U ON U.idUser = H.idUser
WHERE U.nationality in ('french', 'german')
GROUP BY V.idVideo
ORDER BY V.idVideo;

Note the change to GROUP BY V.idVideo, because that's the selected column.

like image 99
jarlh Avatar answered Sep 26 '22 16:09

jarlh


You can do it using conditional aggregation with CASE EXPRESSION :

SELECT V.idVideo,
       COUNT(CASE WHEN  U.nationality = 'french' THEN 1 END) AS nb_fr,
       COUNT(CASE WHEN  U.nationality = 'german' THEN 1 END) AS nb_ge
FROM HISTORY H
INNER JOIN VIDEO V ON V.idVideo = H.idVideo
INNER JOIN USER U ON U.idUser = H.idUser
GROUP BY H.idVideo
ORDER BY V.idVideo
like image 31
sagi Avatar answered Sep 25 '22 16:09

sagi