2013-08-02 120 views
0

我想在3個表中生成一個視圖。SQL創建矩陣表

請參閱下表。

我想要做的就是創建一個視圖,使用col:table的名稱:ItemList作爲新視圖的列的標籤。

我怎樣才能實現這一點使用SQL?

非常感謝您提前。

表:ITEMLIST,這種變化如此頻繁

+----+-------------+ 
| id | name  | 
+----+-------------+ 
| 1 | Apple  | 
| 2 | Orange  | 
| 3 | Banana  | 
| 4 | Kiwi  | 
| 5 | Mango  | 
+----+-------------+ 

表:UserList的

+----+-------------+ 
| id | name  | 
+----+-------------+ 
| 1 | John  | 
| 2 | Mary  | 
| 3 | James  | 
+----+-------------+ 

表:OrderList

+----+------+------+-----+ 
| id | User | Item | qty | 
+----+------+------+-----+ 
| 1 | 1 | 4 | 1 | 
| 2 | 1 | 2 | 2 | 
| 3 | 2 | 1 | 4 | 
| 4 | 1 | 3 | 3 | 
| 5 | 3 | 5 | 1 | 
| 6 | 2 | 2 | 2 | 
+----+------+------+-----+ 

觀點,我想創建

+-------+-------+--------+--------+------+-------+ 
| User | Apple | Orange | Banana | Kiwi | Mango | 
+-------+-------+--------+--------+------+-------+ 
| John |  |  2 |  3 | 1 |  | 
| Mary |  4 |  2 |  |  |  | 
| James |  |  |  |  |  1 | 
+-------+-------+--------+--------+------+-------+ 

回答

1

你必須使用條件求和和動態SQL這個

SET @sql = NULL; 
SELECT 
    GROUP_CONCAT(DISTINCT 
    CONCAT(
     'SUM(CASE WHEN l.Item = ', 
     id, 
     ' THEN l.qty END) `', 
     name, '`' 
    ) 
) INTO @sql 
FROM ItemLIst; 

SET @sql = CONCAT('SELECT u.name, ', @sql, ' 
        FROM OrderList l JOIN UserList u 
         ON l.User = u.id 
        GROUP BY u.name'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

輸出:

 
| NAME | APPLE | ORANGE | BANANA | KIWI | MANGO | 
------------------------------------------------------ 
| James | (null) | (null) | (null) | (null) |  1 | 
| John | (null) |  2 |  3 |  1 | (null) | 
| Mary |  4 |  2 | (null) | (null) | (null) | 

這裏是SQLFiddle演示

現在,您將無法將其包裝到視圖中,但可以將其設置爲存儲過程。

DELIMITER $$ 
CREATE PROCEDURE sp_order_report() 
BEGIN 
    SET @sql = NULL; 
    SELECT 
    GROUP_CONCAT(DISTINCT 
     CONCAT(
     'SUM(CASE WHEN l.Item = ', 
     id, 
     ' THEN l.qty END) `', 
     name, '`' 
    ) 
    ) INTO @sql 
    FROM 
    ItemLIst; 
    SET @sql = CONCAT('SELECT u.name, ', @sql, ' 
         FROM OrderList l JOIN UserList u 
         ON l.User = u.id 
         GROUP BY u.name'); 

    PREPARE stmt FROM @sql; 
    EXECUTE stmt; 
    DEALLOCATE PREPARE stmt; 
END$$ 
DELIMITER ; 

而且使用這樣的:

CALL sp_order_report(); 

這裏是SQLFiddle演示

+0

神奇!這完全是完美的!非常感謝! – Pengin

+0

@Tetsuya你非常歡迎。祝你好運 :) – peterm