2012-02-15 69 views
1

可能重複:
MySQL dynamic cross tab課堂考勤記錄格式SQL查詢

我已經student_record表

------------------------------------------------------------------- 
student_id | semester | schoolyear| name | section | 
------------------------------------------------------------------- 
1   | 1st Semester| 2011-2012 | john | c21  | 
2   | 1st Semester| 2011-2012 | eric | c21  | 
3   | 1st Semester| 2011-2012 | mark | c21  | 

和考勤表

------------------------------------------------------------------- 
attendance_id | stud_id    | week  | 
------------------------------------------------------------------- 
1    | 1     | 02/04/2012 | 
2    | 2     | 02/04/2012 | 
3    | 3     | 02/04/2012 | 
4    | 1     | 02/11/2012 | 
5    | 2     | 02/11/2012 | 
6    | 1     | 02/18/2012 | 
7    | 2     | 02/18/2012 | 
8    | 3     | 02/18/2012 | 

我想用sql來實現這個輸出。

------------------------------------------------------------------- 
student_id | name | 02/04/2012 | 02/11/2012 | 02/18/2012 | 
------------------------------------------------------------------- 
1   | john | present | present | present  | 
2   | erik | present | absent  | present  | 
3   | mark | present | present | present  | 

這對我來說很模糊,任何人都可以幫忙嗎? 我試過了,但沒有奏效。

Select week, 
[02/28/2012], 
[02/29/2012] 
From attendance 
group by student_id 
+2

你** **真正需要的結果集進行調換或者你被允許這樣做,當你準備輸出(以你的編程語言)? – zerkms 2012-02-15 03:22:58

+0

你最好在數據透視查詢中嘗試。請在那裏查看。 http://stackoverflow.com/questions/9104483/sql-query-with-return-columns-based-on-grouping/9104641#9104641 – 2012-02-15 03:28:25

+0

你有PHP的這個標籤。我同意zerkms並會查詢信息,然後在PHP中使用演示文稿進行格式設置。 – mikeY 2012-02-15 03:32:57

回答

0

無論您使用的數據庫如何,您試圖實現的概念都稱爲「數據透視表」。

下面是一個例子爲MySQL: http://en.wikibooks.org/wiki/MySQL/Pivot_table

有些數據庫已經內置的功能爲,請參見下面的鏈接。

的SQLServer: http://msdn.microsoft.com/de-de/library/ms177410.aspx

甲骨文: http://www.dba-oracle.com/t_pivot_examples.htm

您可以隨時手動創建一個支點。只需選擇結果集中的所有聚合,然後從該結果集中進行選擇。

還要檢查這個link,你會得到你的答案被MGA提供...

+0

最糟糕的是,mysql的轉置解決方案基於這樣的事實:在執行查詢之前,您已瞭解列的特徵*。因此它適用於具有固定數量的列的情況,而OP沒有這樣的 – zerkms 2012-02-15 03:49:01

+0

哇!你是所有天才這裏在stackoverflow!非常感謝你給出這個想法。 – 2012-02-15 03:53:18

+0

隨時歡迎...樂於幫助!!! – 2012-02-15 03:54:10