2

大家好,向大家致以热烈的问候,我在 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   |
+----------+-------+------+-----+-----+

我正在尝试编写一个允许我生成表 [查询输出] 的查询。任何帮助都感激不尽。

非常感谢。

4

2 回答 2

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

于 2013-03-11T11:43:21.733 回答
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 演示

于 2013-03-11T11:10:50.630 回答