2013-03-20 23 views
0

我很抱歉如果我在這裏錯過了一些非常明顯的東西,但希望你能幽默我!複雜的查詢融化了我的大腦! Rails和Postgres

我有這些模型

Employee - with id, first_name, last_name 
Shift Type - with id, shift_name 
Date Indices - with id, date 
Locations - with id, location 
Allocated shifts - with employee_id, shift_type_id, date_index_id, location_id 

現在我可以編寫查詢,顯示我分配的變化,並與地點,名稱等加入,但我是什麼是能夠產生一個表,需要日期爲列和員工行產生像這樣

______________________________________________ 

|employee|date 1  |date 2  | date 3 | 
|'dave' |early shift|late shift |day off | 
|'martha'|day off |early shift|early shift| 

名冊等

我敢肯定,我只是很愚蠢,但我怎麼能創造這些「虛擬」列和第鏈接他們對員工?

回答

2

您正在查找「數據透視表」或「交叉表」查詢。 Postgres爲此提供了額外的模塊tablefunc。更多的信息在這個相關的答案:
PostgreSQL Crosstab Query

和許多鏈接到SO類似的問題從那裏。