Sum(Case when)导致多行选择

时间:2013-08-07 18:41:47

标签: postgresql sum case-when

我有一个庞大的客户订单表,我希望运行一个查询,按“user_id”过去13个月按月列出订单。我现在(下面)的工作原理,但不是每个user_id只列出一行,而是为user_id的每个订单列出一行。例如:一个用户在我的生命中总共有42个订单,因此它将他的user_id列为42行,每行只有一个付款。通常情况下,我只是将它放在excel的数据透视表中,但是我超过了百万行限制所以我需要它才是正确的并且没有成功。我希望读出来看起来像这样:

user_id | jul_12 | aug_12 |

123456 | 150.00 | 150.00 |

不是这个:

user_id | jul_12 | aug_12 |

123456 | 0.00 | 150.00 |

123456 | 150.00 | 0.00 |

等。另外40行

SELECT ui.user_id, 
SUM(CASE WHEN date_part('year', o.time_stamp) = 2012 AND date_part('month', o.time_stamp) = 07 THEN o.amount ELSE 0 END) jul_12,
SUM(CASE WHEN date_part('year', o.time_stamp) = 2012 AND date_part('month', o.time_stamp) = 08 THEN o.amount ELSE 0 END) aug_12,
FROM orders o JOIN users_info ui ON ui.user_id = o.user_id
WHERE user_id = '123456'
GROUP BY ui.user_id, o.time_stamp;

1 个答案:

答案 0 :(得分:3)

尝试类似:

SELECT ui.user_id, 
SUM(CASE WHEN date_part('year', o.time_stamp) = 2012 AND date_part('month', o.time_stamp) = 07 THEN o.amount ELSE 0 END) jul_12,
SUM(CASE WHEN date_part('year', o.time_stamp) = 2012 AND date_part('month', o.time_stamp) = 08 THEN o.amount ELSE 0 END) aug_12,
FROM orders o JOIN users_info ui ON ui.user_id = o.user_id
WHERE user_id = '123456'
GROUP BY ui.user_id;

您为每个订单获得一行,因为您按o.time_stamp进行分组,每个订单的时间戳都不同。

查询的较短版本:

SELECT ui.user_id, 
SUM(CASE WHEN date_trunc('month', o.time_stamp) = to_date('2012 07','YYYY MM') THEN o.amount END) jul_12,
SUM(CASE WHEN date_trunc('month', o.time_stamp) = to_date('2012 08','YYYY MM') THEN o.amount END) aug_12,
FROM orders o 
JOIN users_info ui ON ui.user_id = o.user_id
WHERE ui.user_id = '123456'
GROUP BY ui.user_id;