在一个表中满足条件并仍然联接到另一个表时,如何查找并汇总它们?

时间:2018-10-04 23:32:04

标签: postgresql

我想显示有多少客户ID的收据超过50美元(从“收据”表中找到:列名“ customer_id”,列名:“ total_price”),然后将其加入到具有列出状态的列。我想计算每个customer_id的“ rcpt_over_50”并列出其状态。 这是我的东西:

SELECT customers.state, round(avg(over_50),2) AS rcpts_over_50
FROM ( 
     SELECT receipts.customer_id, receipts.total_price, customers.state,
     CASE 
         WHEN CAST(total_price AS numeric) >= 50 THEN 1
         ELSE 0
         END AS rcpts_over_50
     FROM receipts
     LEFT JOIN customers
     ON receipts.customer_id = receipts.customer_id) as TEMP
 GROUP BY customers.state

我不断收到错误消息:“关系“收据”不存在”

我该怎么办

收据表:

receipt_id customer_id total_price
0000      00003         3.00    
0001      00002        75.25    
0002      00003        50.00
0003      00002        54.25   
0004      00010        60.00

客户:

customer_id state  
00003       NY    
00002       OK    
00010       NY     

所需的输出显示每个客户ID超过50张的收据数量及其各自的状态:

customer_id rcpt_over_50    state
00002       2               OK
00003       1               NY
00010       1               NY

1 个答案:

答案 0 :(得分:1)

demo:db<>fiddle

SELECT c.customer_id, COUNT(*) as rcpt_over_50, c.state -- B
FROM receipts r
JOIN customers c
ON c.customer_id = r. customer_id                       -- A
     AND r.total_price >= 50
GROUP BY c.customer_id, c.state
ORDER BY rcpt_over_50 DESC, customer_id                 -- C

A :(内部)联接消除了所有带有total_cost < 50的收据。

B:然后,您只需要GROUPcustomer_id并计算行数。

C:最后,您可以对结果进行排序(在这里,我使用了您在问题中提到的降序)


请注意,以您的方式存储ID从来不是一个好主意。请使用简单的整数类型而不是左填充文本。计算和存储效率更高。考虑一下大于100000的ID