【发布时间】:2014-09-15 14:49:00
【问题描述】:
我需要做一个 JasperReport。我需要显示的是帐户进程总数,分为weekly intervals 和activated 的number 和declined 帐户。
到目前为止我得到的每周间隔查询:
SELECT *
FROM account_details
WHERE DATE date_opened = DATE_ADD(2014-01-01, INTERVAL(1-DAYOFWEEK(2014-01-01)) +1 DAY)
这似乎是正确的,但POSTGRES 不正确。它一直在抱怨1-DAYOFWEEK。以下是我希望实现的目标:
更新 它很丑陋,但我不知道有什么更好的。 Id 完成了这项工作。但不知道它是否可以重新分解,至少看起来更好。我现在也不知道如何处理除以零。
SELECT to_char(d.day, 'YYYY/MM/DD - ') || to_char(d.day + 6, 'YYYY/MM/DD') AS Month
, 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
, SUM(CASE WHEN LOWER(situation) LIKE '%declined%' OR LOWER(situation) LIKE '%active%' THEN 1 ELSE 0 END) AS Total
, to_char( 100.0 *( (SUM(CASE WHEN LOWER(situation) LIKE '%active%' THEN 1 ELSE 0 END)) / (SUM(CASE WHEN LOWER(situation) LIKE '%declined%' OR LOWER(situation) LIKE '%active%' THEN 1 ELSE 0 END))::real) , '99.9') AS percent_activated
, to_char( 100.0 *( (SUM(CASE WHEN LOWER(situation) LIKE '%declined%' THEN 1 ELSE 0 END)) / (SUM(CASE WHEN LOWER(situation) LIKE '%declined%' OR LOWER(situation) LIKE '%active%' THEN 1 ELSE 0 END))::real) , '99.9') AS percent_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;
【问题讨论】:
-
文字日期和时间戳值在单引号之间,例如
'2014-01-01'。 -
虽然
SELECT 2014-01-01有效,但它的计算结果为2012——你也完全误解了什么是文字,什么是函数调用——看看在这里:postgresql.org/docs/current/static/… -- 列值和表达式已经有一个类型,它们不需要注意,但有时需要casted postgresql.org/docs/current/static/… -
“小提琴”链接不是小提琴,而是另一个图像。可能是链接混淆了?
-
好的,现在有一个fiddle,但它与问题无关。
标签: sql postgresql aggregate-functions dateinterval