如何使用交叉表在正确的列中获取值?

时间:2016-08-03 08:43:33

标签: postgresql crosstab

我有一个交叉表SQL,我没有得到预期的结果作为输出。我得到了第一列的所有值。这是我的sql:

select * from crosstab 
('select p.name::text as product,
 pc.name as prod_cat,
 sum( ms.qtyonhand) as total_stock from adempiere.m_product p 
 join adempiere.m_product_category pc on p.m_product_category_id=pc.m_product_category_id 
 join adempiere.m_storage ms on ms.m_product_id=p.m_product_id 
 group by prod_cat,product order by 3 desc') as ct 

(product text,
 "ELECTRICAL & ELECTRONIC ITEMS" numeric,
 "ACADEMICS BOOKS" numeric,
 "Standard" numeric,
 "FOOD AND BEVERAGES" numeric,
 "Possibly Product Category" numeric, 
 "Pharmacy Medicine" numeric,
  "COMPUTER & ACCESSORIES" numeric) 
limit 10

这是我得到的输出:http://i.stack.imgur.com/w6gc5.png

这是我要找的输出:

product              | Electricals |   Electronics |  Food & Beverages |  Cosmetics |  Hardwares  
---------------------|-------------|---------------|-------------------|------------|-------------
Samsung-WM           |             |     4552      |                   |            |          
Videocon-Refridge    |             |     1254      |                   |            |             
Philips-CFL Bulbs    |   5677      |               |                   |            |             
Head&shoulder Shampoo|             |               |                   |     4567   |             
Candysweet           |             |               |       5678        |            |             
Icecreams            |             |               |       6785        |            |             
Paints               |             |               |                   |            |      9876   
Taps                 |             |               |                   |            |     10987   
Electrical wires     |  18796      |               |                   |            |             

如何修改查询以获得正确的结果?

1 个答案:

答案 0 :(得分:0)

您应该将该函数用于两个查询:crosstab(text source_sql, text category_sql)。 在第二个查询中,按所需顺序选择所有可能的类别值。

简单示例 - 我的家庭预算:

create table expenses (subject text, person text, cost int);
insert into expenses values
('dress', 'wife', 200),
('toy', 'son', 100),
('beer', 'me', 50);

要点:

select * 
from crosstab (
    $ct$
    select * from expenses
    order by 1, 2
    $ct$
    ) as ct (subject text, wife int, son int, me int);

 subject | wife | son | me 
---------+------+-----+----
 beer    |   50 |     |   
 dress   |  200 |     |   
 toy     |  100 |     |   
(3 rows)

嗯,这不是我所信任的。

当查询生成带孔的数据时,您应该告诉crosstab()它如何识别哪个value属于哪个category

select * 
from crosstab (
    $ct$
    select * from expenses
    order by 1, 2
    $ct$,
    $ct$ 
    select person from expenses
    order by 1 desc
    $ct$
    ) as ct (subject text, wife int, son int, me int);

 subject | wife | son | me 
---------+------+-----+----
 beer    |      |     | 50
 dress   |  200 |     |   
 toy     |      | 100 |   
(3 rows)        

第二个查询只返回一个类别列表:'wife', 'son', 'me'(顺序很重要)。 您也可以使用values ('wife'), ('son'), ('me')

相关问题