postgresql中的复杂查询

时间:2013-03-11 11:02:49

标签: postgresql pivot

您好,热烈的问候你们所有人, 我在posgresql中编写复杂查询时遇到了一些挑战。事实是我在编写这个特定的查询期间遇到了问题,并且需要您的帮助。让我们来看看。

这是我的表格

[products_tb]         [client_tb]          [sales_tb]
+--------------+      +-------------+      +-------------+--------------+-----+
| product_name |      | client_name |      | client_name | product_name | qty | 
+--------------+      +-------------+      +-------------+--------------+-----+
| shoe         |      | john        |      | john        | shoe         | 20  |
+--------------+      +-------------+      +-------------+--------------+-----+
| belt         |      | bob         |      | john        | belt         | 9   |
+--------------+      +-------------+      +-------------+--------------+-----+
                      | kim         |      | bob         | shoe         | 2   |
                      +-------------+      +-------------+--------------+-----+
                                           | bob         | belt         | 98  |
                                           +-------------+--------------+-----+
                                           | kim         | shoe         | 46  |
                                           +-------------+--------------+-----+
                                           | kim         | belt         | 3   |
                                           +-------------+--------------+-----+


[query output] # this output will be displayed using php and html
+----------+-------+------+-----+-----+
| products | Total | john | bob | kim |
+----------+-------+------+-----+-----+
| shoe     | 68    | 20   | 2   | 46  |
+----------+-------+------+-----+-----+
| belt     | 110   | 9    | 98  | 3   |
+----------+-------+------+-----+-----+

我正在尝试编写一个允许我生成表[query output]的查询。任何帮助将不胜感激。

非常感谢你。

2 个答案:

答案 0 :(得分:0)

以下是使用标准SQL执行此操作的一种方法:

SELECT st.product_name AS products,
       SUM(st.qty) AS Total,
       (SELECT SUM(st_john.qty)
        FROM sales_tb st_john
        WHERE client_name = 'john' AND st_john.product_name = st.product_name) AS john,
       (SELECT SUM(st_bob.qty)
        FROM sales_tb st_bob
        WHERE client_name = 'bob' AND st_bob.product_name = st.product_name) AS bob,
       (SELECT SUM(st_kim.qty)
        FROM sales_tb st_kim
        WHERE client_name = 'kim' AND st_kim.product_name = st.product_name) AS kim
FROM sales_tb st
GROUP BY product_name

请参阅SQL Fiddle Demo

答案 1 :(得分:0)

不使用cross_tab的版本:

select p.product_name, sum(s.qty), 
sum(CASE WHEN c.client_name='john' THEN s.qty END) as john,
sum(CASE WHEN c.client_name='bob' THEN s.qty END) as bob,
sum(CASE WHEN c.client_name='kim' THEN s.qty END) as kim
   from products_tb AS p 
   JOIN sales_tb AS s ON p.product_name=s.product_name
   JOIN clients_tb AS c ON c.client_name=s.client_name
   GROUP BY p.product_name;

http://sqlfiddle.com/#!12/afc9a/10