2

この形式のデータを db に持っている

---------------------------------------------
count | margin |    date    | week | day    |
---------------------------------------------
 230  |   140  | 2013-01-01 |  0   | Monday  |
----------------------------------------------
 500  |   340  | 2013-01-02 |  0   | Tuesday  |
----------------------------------------------
 200  |   240  | 2013-01-08 |  1   | Monday  |
----------------------------------------------

要求出力は

-----------------------------------------------------------
|   week  |   monday  |  tuesday  |  wednesday  | .........
-----------------------------------------------------------
|    0    |  230:140  |  500:340  |
-----------------------------------------------------------   
|    1    |  200:240  | 
-----------------------------------------------------------

どんな助けでも大歓迎です

4

1 に答える 1

2

次の静的クエリを試してください。

SELECT Week
    ,GROUP_CONCAT(CASE WHEN day = 'Monday' 
                       THEN CONCAT(count,':',margin) ELSE NULL END) AS Monday
    ,GROUP_CONCAT(CASE WHEN day = 'Tuesday' 
                       THEN CONCAT(count,':',margin) ELSE NULL END) AS Tuesday
    ,GROUP_CONCAT(CASE WHEN day = 'Wednesday' 
                       THEN CONCAT(count,':',margin) ELSE NULL END) AS Wednesday
    ,GROUP_CONCAT(CASE WHEN day = 'Thursday' 
                       THEN CONCAT(count,':',margin) ELSE NULL END) AS Thursday
    ,GROUP_CONCAT(CASE WHEN day = 'Friday' 
                       THEN CONCAT(count,':',margin) ELSE NULL END) AS Friday
    ,GROUP_CONCAT(CASE WHEN day = 'Saturday' 
                       THEN CONCAT(count,':',margin) ELSE NULL END) AS Saturday
    ,GROUP_CONCAT(CASE WHEN day = 'Sunday' 
                       THEN CONCAT(count,':',margin) ELSE NULL END) AS Sunday
FROM MyTable 
GROUP BY Week

次の動的クエリも使用できます。

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'GROUP_CONCAT(CASE WHEN `day` = ''',
      `day`,
      ''' THEN CONCAT(count,'':'',margin) ELSE NULL END) AS `',
      `day`, '`'
    )
  ) INTO @sql
FROM MyTable;

SET @sql = CONCAT('SELECT Week, ', @sql,'
                     FROM MyTable
                    GROUP BY Week
                  ');

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

このSQLFiddleを参照してください

于 2013-07-20T07:55:22.153 に答える