2016-08-03 68 views
0

我有一個交叉表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  |    |     |   |    

如何修改我的查詢來獲取適當的結果?

+0

不發佈圖片發佈數據。你期望的輸出是什麼? – e4c5

回答

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')

+0

你能舉個例子嗎? –

+0

非常感謝您的幫助..它工作完美。 –