簡體   English   中英

如何在html中以特定格式顯示sql數據

[英]How to display sql data in a specific format in html

我在Mysql中有以下格式的數據:

   name sub
----------------
    a   maths
    a   science
    a   history
    b   maths
    b   science
    a   computer
    a   english
    c   computer
    c   history
    b   history
    c   maths

我打算以HTML格式顯示此數據:

Name    maths   science history computer  english
a          y        y       y       y         y
b          y        y       y       n         n
c          y        n       y       y         n

除了透視表方法外,如何制定我的SQL查詢?

如果要動態創建列,則可以使用動態數據透視。

使用GROUP_CONCAT創建樞軸列,然后Concat SQL執行語法,動態執行它。

SET @sql = NULL;

SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'COALESCE(MAX(CASE WHEN sub = ''',
      sub,
      ''' then ''y'' end),''n'') AS ',
      sub
    )
  ) INTO @sql
FROM T;

SET @sql = CONCAT('SELECT name, ', @sql, ' 
                  FROM T 
                  GROUP BY name');

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

sqlfiddle

結果

   name   maths science history computer    english
    a       y       y       y     y          y
    b       y       y       y     n          n
    c       y       n       y     y          n

我在這里發現了類似的情況。 讓我簡要介紹一下問題和解決方案:

問題:

轉換為:

select * from history;

+--------+----------+-----------+
| hostid | itemname | itemvalue |
+--------+----------+-----------+
|      1 | A        |        10 |
|      1 | B        |         3 |
|      2 | A        |         9 |
|      2 | C        |        40 |
+--------+----------+-----------+

變成這個:

select * from history_itemvalue_pivot;

+--------+------+------+------+
| hostid | A    | B    | C    |
+--------+------+------+------+
|      1 |   10 |    3 |    0 |
|      2 |    9 |    0 |   40 |
+--------+------+------+------+

解:

在本文中,這是作者執行的步驟:

  1. 選擇感興趣的列,即y值和x值
  2. 用額外的列擴展基本表-每個x值一個
  3. 分組並匯總擴展表-每個y值一組
  4. (可選)整理匯總表

這是全文: MySQL-行到列

希望能幫助到你。

問候,

您可以在SQL中使用條件聚合:

SELECT name,  
       MAX(CASE WHEN sub = 'maths'   then 'y' ELSE 'n' END) AS maths,
       MAX(CASE WHEN sub = 'science' then 'y' ELSE 'n' END) AS science,
       MAX(CASE WHEN sub = 'history' then 'y' ELSE 'n' END) AS history,
       MAX(CASE WHEN sub = 'computer'then 'y' ELSE 'n' END) AS computer,
       MAX(CASE WHEN sub = 'english' then 'y' ELSE 'n' END) AS english
FROM table t
GROUP BY name;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM