从数据库列创建行

时间:2018-07-14 08:49:31

标签: python sql mariadb pivot-table

目前,我已按照以下方式从数据库中检索了此数据,

—network

如何将表格更改为类似的内容?

outlier(sample.data, plot = TRUE, col.main = NA)
title("My Title")

我通过使用peewee从数据库中连接多个表来获取数据 下面是我检索和格式化数据的完整代码

+------------+--------------+-------+-----+-------------+-----------+------------------+-----------------+
    | Monitor ID | Casting Date | Label | AGE | Client Name |  Project  | Average Strength | Average Density |
    +------------+--------------+-------+-----+-------------+-----------+------------------+-----------------+
    |    1082    |  2018-07-05  |  b52  |  1  |  Trial Mix  | Trial Mix |      21.78       |      2.436      |
    |    1082    |  2018-07-05  |  b52  |  2  |  Trial Mix  | Trial Mix |      33.11       |      2.406      |
    |    1082    |  2018-07-05  |  b52  |  4  |  Trial Mix  | Trial Mix |      43.11       |      2.447      |
    |    1082    |  2018-07-05  |  b52  |  8  |  Trial Mix  | Trial Mix |      48.22       |      2.444      |
    |    1083    |  2018-07-05  |  B53  |  1  |  Trial Mix  | Trial Mix |      10.44       |      2.421      |
    |    1083    |  2018-07-05  |  B53  |  2  |  Trial Mix  | Trial Mix |       20.0       |      2.400      |
    |    1083    |  2018-07-05  |  B53  |  4  |  Trial Mix  | Trial Mix |      27.78       |      2.397      |
    |    1083    |  2018-07-05  |  B53  |  8  |  Trial Mix  | Trial Mix |      33.33       |      2.409      |
    |    1084    |  2018-07-05  |  B54  |  1  |  Trial Mix  | Trial Mix |      12.89       |      2.430      |
    |    1084    |  2018-07-05  |  B54  |  2  |  Trial Mix  | Trial Mix |      24.44       |      2.427      |
    |    1084    |  2018-07-05  |  B54  |  4  |  Trial Mix  | Trial Mix |      34.22       |      2.412      |
    |    1084    |  2018-07-05  |  B54  |  8  |  Trial Mix  | Trial Mix |      41.56       |      2.501      |
    +------------+--------------+-------+-----+-------------+-----------+------------------+-----------------+

1 个答案:

答案 0 :(得分:1)

您必须透视数据,因为MariaDB没有透视,您可以在sql中完成它:

SELECT
    MonitorID,
    CastingDate,
    Label,
    ClientName,
    Project,
    SUM(IF(Age=1, AverageStrength, 0)) AS AvgStr1,
    SUM(IF(Age=2, AverageStrength, 0)) AS AvgStr2,
    SUM(IF(Age=4, AverageStrength, 0)) AS AvgStr4,
    SUM(IF(Age=8, AverageStrength, 0)) AS AvgStr8,
    SUM(IF(Age=1, AverageDensity, 0)) AS AvgDensity1,
    SUM(IF(Age=2, AverageDensity, 0)) AS AvgDensity2,
    SUM(IF(Age=4, AverageDensity, 0)) AS AvgDensity4,
    SUM(IF(Age=8, AverageDensity, 0)) AS AvgDensity8
FROM
    YourTable
GROUP BY MonitorID, CastingDate, Label, ClientName, Project, Age
ORDER BY MonitorID, CastingDate;