结合select语句以正确格式输出SQLite3

时间:2017-05-28 07:57:37

标签: sqlite

我想将这些输出组合成一个表输出而不是两个。我还需要将行的名称从数字更改为Protected和Non-Protected。

这是我的代码:

SELECT
MediaTypeID Media, count(MediaTypeID) FROM Track t
WHERE MediaTypeID = 2 OR MediaTypeID = 3;
SELECT
MediaTypeID Media, count(MediaTypeID) FROM Track t
WHERE MediaTypeID = 1 OR MediaTypeID = 4;

这是我的出局:

SMedia       count(MediaTypeID)
----------  ------------------
2           451
Media       count(MediaTypeID)
----------  ------------------
4           3041

这是所需的输出类型:

Media            Tracks         
---------------  ---------------
Protected        451            
non-Protected    3052

1 个答案:

答案 0 :(得分:0)

在一般情况下,您可以将多个查询(具有相同数量的输出列)与UNION ALL合并:

SELECT 'Protected' AS Media, COUNT(*) FROM Track WHERE MediaTypeID IN (2, 3)
UNION ALL
SELECT 'non-Protected'     , COUNT(*) FROM Track WHERE MediaTypeID IN (1, 4);

但是,要运行具有多个组的聚合函数,只需使用GROUP BY:

SELECT CASE WHEN MediaTypeID IN (2, 3) THEN 'Protected'
            ELSE                            'non-Protected'
       END AS Media,
       COUNT(*)
FROM Track
GROUP BY Media;