PG:如果结果为0,如何显示此查询的总计数

时间:2017-06-24 16:53:47

标签: postgresql

我有一个名为ngAfterViewInit() { postscribe('#adv', `<script type="text/javascript" language="javascript"> var aax_size='728x90'; var aax_pubname = 'XXXXXXXX'; var aax_src='302'; </script> <script type="text/javascript" language="javascript" src="http://c.amazon-adsystem.com/aax2/assoc.js"></script>`);} 的postgres 9.6表,其中一个名为selected_media的列设置为_typebook

我想在1行中选择每种类型的movie,如下所示:

COUNT

要做到这一点,我有这个问题:

25 | 715

问题是2折:

  1. 如果该列中的总和恰好为0(未选中),我希望每列都显示该<_>的总计数。这是因为UI / UX声明&#34;选择0本书或电影与选择所有书籍或#34; 相同。

  2. 它需要很快,这个表中会有数百万行

1 个答案:

答案 0 :(得分:1)

您可以将COUNTFILTER子句一起使用:

SELECT 
COUNT(*) FILTER (WHERE _type = 'book') AS books_count,
COUNT(*) FILTER (WHERE _type = 'movie') AS movies_count
FROM selected_media
WHERE subscriber_id = $1;

更多信息here

<小时/> 的修改

使用嵌套子查询来满足您的第一需求:

SELECT
    CASE books_count WHEN 0 THEN (SELECT COUNT(*) FROM selected_media WHERE _TYPE = 'book') ELSE books_count END AS books_count_final,
    CASE movies_count WHEN 0 THEN (SELECT COUNT(*) FROM selected_media WHERE _TYPE = 'movie') ELSE movies_count END AS movies_count_final   
FROM 
    (
    SELECT 
        COUNT(*) FILTER (WHERE _type = 'book') AS books_count,
        COUNT(*) FILTER (WHERE _type = 'movie') AS movies_count
    FROM 
        selected_media
    WHERE 
        subscriber_id = $1
    ) AS sub_query

或使用CTE

WITH selected_media_sub AS (
    SELECT 
        COUNT(*) FILTER (WHERE _type = 'book') AS books_count,
        COUNT(*) FILTER (WHERE _type = 'movie') AS movies_count
    FROM 
        selected_media
    WHERE 
        subscriber_id = $1
 )

SELECT
    CASE books_count WHEN 0 THEN (SELECT COUNT(*) FROM selected_media WHERE _TYPE = 'book') ELSE books_count END AS books_count_final,
    CASE movies_count WHEN 0 THEN (SELECT COUNT(*) FROM selected_media WHERE _TYPE = 'movie') ELSE movies_count END AS movies_count_final   
FROM selected_media_sub;

顺便说一句,如果您只需要一个非零计数,您可以执行以下操作:

SELECT 
    COALESCE(NULLIF(COUNT(*) FILTER (WHERE _type = 'book'), 0), 1) AS books_count,
    COALESCE(NULLIF(COUNT(*) FILTER (WHERE _type = 'movie'), 0), 1) AS movies_count
FROM 
    selected_media
WHERE 
    subscriber_id = $1