如何在列中划分句点

Posted

技术标签:

【中文标题】如何在列中划分句点【英文标题】:How to divide a period in columns 【发布时间】:2021-12-03 06:25:03 【问题描述】:

我正在尝试创建一个查询,其中第一列显示公司列表,其他 3 列显示他们每月的收入。我就是这样做的:

WITH time_frame AS
  (SELECT date_trunc('month',NOW())-interval '0 week'),
  
  
  time_frame1 AS
  (SELECT date_trunc('month',NOW())-interval '1 month'),
  
  time_frame2 AS
  (SELECT date_trunc('month',NOW())-interval '2 month')


select table1.company_name,

            (CASE
               WHEN  table2.date_of_transaction = (SELECT * FROM time_frame2) THEN sum(table2.amount)
               ELSE NULL
           END) AS "current week - 2",
           
              (CASE
               WHEN  table2.date_of_transaction = (SELECT * FROM time_frame1) THEN sum(table2.amount)
               ELSE NULL
           END) AS "current week - 1",
           
           
       (CASE
               WHEN  table2.date_of_transaction = (SELECT * FROM time_frame2) THEN 
 sum(table2.amount)
               ELSE NULL
           END) AS "current week - 2"




from table1
join table2 on table2.table1_id = table.id
where table1.company_joined >= '04-20-2019'

group by 1

当我执行表时,会出现:运行查询时出错:列“table2.date_of_transaction”必须出现在 GROUP BY 子句中或用于聚合函数第 15 行:WHEN table2.date_of_transaction = (SELECT * FROM time_frame)嗯……^

您对如何解决它有任何想法吗?谢谢。

company name month1 month2
name 1 £233 £343
name 2 £243 £34
name 3 £133 £43

【问题讨论】:

尝试删除group by 1 【参考方案1】:

您可以使用filter() 运算符来简化语句

select t1.company_name,
       sum(t2.amount) filter (where t2.date_of_transaction = date_trunc('month',NOW())-interval '2 month'),
       sum(t2.amount) filter (where t2.date_of_transaction = date_trunc('month',NOW())-interval '1 month'),
       sum(t2.amount) filter (where t2.date_of_transaction = date_trunc('month',NOW()))
from table1 t1
  join table2 t2 on t2.table1_id = t1.id
where t1.company_joined >= date '2019-04-20'
group by t1.company_name;

如果您真的想将日期范围放入 CTE,您只需要一个:

with dates (r1, r2, r3) as (
  values 
    (date_trunc('month',NOW())-interval '2 month',
     date_trunc('month',NOW())-interval '1 month',
     date_trunc('month',NOW()))
)
select t1.company_name,
       sum(t2.amount) filter (where t2.date_of_transaction = d.r1),
       sum(t2.amount) filter (where t2.date_of_transaction = d.r2),
       sum(t2.amount) filter (where t2.date_of_transaction = d.r3)
from table1 t1
  cross join dates d
  join table2 t2 on t2.table1_id = t1.id
where t1.company_joined >= date '2019-04-20'
group by t1.company_name
;

CTE dates 返回包含三列的单行,因此交叉连接不会更改结果行数。

【讨论】:

感谢您的回复。 “过滤器”是什么意思?它在 Postgresql 中不被识别为函数 @RMolok:那么你使用的是过时的 Postgres 版本 好的,谢谢,我想我用你的答案和案例解决了每个月作为过滤器的问题

以上是关于如何在列中划分句点的主要内容,如果未能解决你的问题,请参考以下文章

UltraWebGrid:如何在列中使用下拉列表

MySQL:如何在列中选择具有某些值的 ID [重复]

PySpark:如何在列中使用 Or 进行分组

如何在列中显示饼图的图例?

如何使用 SQL LIKE 运算符在列中搜索精确模式?

Telerik MVC Grid:如何在列中使用 DropDownList?