我如何在PostgreSQL中编写此查询?

时间:2016-04-23 14:56:08

标签: mysql sql database postgresql

来自MySQL的原创。在那里,我想通过条件知道有多少个单独的行:

SELECT
sum(status='waiting'),
sum(source='twitter'),
sum(no_send_before <= '2009-05-28 03:17:50'),
sum(tries <= 20),
count(*)
FROM table_name


*************************** 1. row ***************************
                      sum(status ='waiting'): 550
                       sum(source='twitter'): 37271
sum(no_send_before <= '2009-05-28 03:17:50'): 36975
                            sum(tries <= 20): 36569
                                    count(*): 37271

1 个答案:

答案 0 :(得分:1)

对于两个数据库之间一致的查询,请使用case

SELECT sum(case when status='waiting' then 1 else 0 end),
       sum(case when source='twitter' then 1 else 0 end),
       sum(case when no_send_before <= '2009-05-28 03:17:50' then 1 else 0 end),
       sum(case when tries <= 20 then 1 else 0 end),
       count(*)
FROM table_name;

对于更短的Postgres特定语法:

SELECT sum((status='waiting')::int),
       sum((source='twitter')::int)),
       sum((no_send_before <= '2009-05-28 03:17:50'))::int),
       sum((tries <= 20))::int),
       count(*)
FROM table_name
相关问题