sql – 将两个选择查询合并为一个

前端之家收集整理的这篇文章主要介绍了sql – 将两个选择查询合并为一个前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有三个表:历史,视频和用户.
以下两个查询为每个视频显示法国用户或德国用户的观看次数
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;

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

但是如何将这两个查询结合起来只有一个?
我想要这样的东西:

idVideo | nb_fr | nb_ge
-----------------------
    1   |   5   |   4
    2   |   3   |   6
    3   |   2   |   8
    4   |   3   |   3

解决方法

用例表达式执行条件聚合:
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;

请注意对GROUP BY V.idVideo的更改,因为这是所选列.

原文链接:https://www.f2er.com/mssql/77634.html

猜你在找的MsSQL相关文章