从一列中捕获和汇总字符串值?

时间:2014-09-16 07:40:35

标签: sql postgresql

FIDDLE

我有这个查询(在Erwin Brandstetter先生的帮助下),它打印周间隔。

SELECT to_char(d.day, 'YYYY/MM/DD  -  ') || to_char(d.day + 6, 'YYYY/MM/DD') AS week
FROM   (
   SELECT day::date
   FROM   generate_series('2014-08-01'::date, '2014-09-14'::date, interval '1 week') day
   ) d
JOIN   account_details a ON a.date_opened >= d.day 
                        AND a.date_opened <  d.day + 6
GROUP  BY d.day;

但是我想根据特定列中的值附加并添加其他信息

这应该是最终结果。 enter image description here

因此activateddeclined的信息来自一个字符串列situation
我试图从列中捕获regexp_matches匹配值并总结捕获量(下图),但它没有做到这一点。

请问,您如何从一列中捕获和汇总字符串值?

SELECT to_char(d.day, 'YYYY/MM/DD  -  ') || to_char(d.day + 6, 'YYYY/MM/DD') AS week
     , SUM(SELECT regexp_matches(situation, 'active'))     AS activated
     , SUM(SELECT regexp_matches(situation, 'declined'))     AS declined
FROM   (
   SELECT day::date
   FROM   generate_series('2014-08-01'::date, '2014-09-14'::date, interval '1 week') day
   ) d
JOIN   account_details a ON a.date_opened >= d.day 
                        AND a.date_opened <  d.day + 6
GROUP  BY d.day;

示例数据 enter image description here 所以有更多的列,但这里只使用了两个。 open_datesituation
situation也有很多不同的选项,但只会使用ActiveDeclined

FIDDLE

1 个答案:

答案 0 :(得分:1)

不确定这是否有效,但您可能想要计算匹配次数:

SELECT to_char(d.day, 'YYYY/MM/DD  -  ') || to_char(d.day + 6, 'YYYY/MM/DD') AS week
     , SUM(CASE WHEN LOWER(situation) LIKE '%active%' THEN 1 ELSE 0 END)     AS activated
     , SUM(CASE WHEN LOWER(situation) LIKE '%declined%' THEN 1 ELSE 0 END) AS declined
FROM   (
   SELECT day::date
   FROM   generate_series('2014-08-01'::date, '2014-09-14'::date, interval '1 week') day
   ) d
JOIN   account_details a ON a.date_opened >= d.day 
                        AND a.date_opened <  d.day + 6
GROUP  BY d.day;