Postgres将值组合在一起而不是具有单独的值

时间:2017-06-21 23:52:50

标签: sql postgresql postgresql-9.3 postgresql-9.2

我在下面编写了这段代码,我想制作一些与此类似的东西:

Days Before Stay  | Number of Submits
-------------------------------------
0-9        |        11
10-19      |        14
20-29      |         3

我创建了一个选择case语句,它会产生语法错误

WITH sql_runner_query AS (SELECT 
events_raw.properties ->> 'days_before_stay' AS "Number of Days 
Before Stay",
COUNT(CASE WHEN ((events_raw.properties ->> 'event_type') LIKE 
'fs_mystay_activity_submit') THEN 1 ELSE NULL END) AS "Number of 
Activities Processed"
FROM events_raw

WHERE (events_raw.account_id  = 7270737) AND 
((((events_raw.properties ->> 'days_before_stay') IS NOT NULL) AND 
((events_raw.properties ->> 'days_before_stay') IS NOT NULL AND 
LENGTH(events_raw.properties ->> 'days_before_stay') <> 0 ))) AND 
(events_raw.account_id  > 0)
GROUP BY 1
ORDER BY 1 desc 
LIMIT 500
)

(SELECT 
 events_raw.properties ->> 'days_before_stay' AS "Number of Days 
Before Stay",
COUNT(CASE WHEN ((events_raw.properties ->> 'event_type') LIKE 
'fs_mystay_activity_submit') THEN 1 ELSE NULL END) AS "Number of 
Activities Processed"
 case when 'days_before_stay' >= 0 and <=10 then '0-10'
 else
'11-300' end as range
FROM events_raw

GROUP BY 1,2
ORDER BY 1 DESC
LIMIT 5000

1 个答案:

答案 0 :(得分:0)

查询第二部分中的

(SELECT不应该有(

您在这里缺少逗号:

COUNT(CASE WHEN ((events_raw.properties ->> 'event_type') LIKE 'fs_mystay_activity_submit') THEN 1 ELSE NULL END) AS "Number of Activities Processed" , -- add a comma here case when 'days_before_stay' >= 0 and <=10 then '0-10' else '11-300' end as range

查询的其他问题:

  • 为什么要按COUNT()进行分组?
  • 为什么你有一个名为sql_runner_query的CTE,然后在主查询中没有引用它?