3

我想根据周将多行转换为单行。它应该如下所示。谁能帮我?

id      |   Weight   |  Created   |
 1      |    120     | 02-04-2012 |
 2      |    110     | 09-04-2012 |
 1      |    100     | 16-04-2012 |
 1      |    130     | 23-04-2012 |
 2      |    140     | 30-04-2012 |
 3      |    150     | 07-05-2012 |

结果应如下所示:

id      |   Weight_week1  | Weight_week2  |  weight_week3  | weight_week4  |
 1      |     120         |     100       |      130       |               |
 2      |     110         |     140       |                |               |
 3      |     150         |               |                |               |

提前致谢。

4

4 回答 4

1

如果这是一张桌子,那么

SELECT GROUP_CONCAT(weight) as Weight,
        WEEK(Created) as Week
Group by Week(Created)

这会给你一行,每个都有周 id 和逗号分隔的 whights

于 2012-05-07T11:31:39.760 回答
1

你可以这样做:

SELECT
    t.id,
    SUM(CASE WHEN WeekNbr=1 THEN Table1.Weight ELSE 0 END) AS Weight_week1,
    SUM(CASE WHEN WeekNbr=2 THEN Table1.Weight ELSE 0 END) AS Weight_week2,
    SUM(CASE WHEN WeekNbr=3 THEN Table1.Weight ELSE 0 END) AS Weight_week3,
    SUM(CASE WHEN WeekNbr=4 THEN Table1.Weight ELSE 0 END) AS Weight_week4
FROM
    (
    SELECT  
        (
           WEEK(Created, 5) - 
           WEEK(DATE_SUB(Created, INTERVAL DAYOFMONTH(Created) - 1 DAY), 5) + 1 
        )as WeekNbr,
        Table1.id,
        Table1.Weight,
        Table1.Created
    FROM
        Table1
    ) AS t
GROUP BY
    t.id

我不知道您是否想要AVG, SUM,MAX或者MIN但是您可以将聚合更改为您想要的。

有用的参考资料:

于 2012-05-07T11:16:52.190 回答
0

您不能像那样即时创建字段,但可以对它们进行分组。

用于GROUP_CONCAT提供带有分隔符的结果,您可以稍后将其分隔。

于 2012-05-07T11:05:52.540 回答
0

你也可以这样做:

SELECT id, created, weight, (
    SELECT MIN( created ) FROM weights WHERE w.id = weights.id
) AS `min` , round( DATEDIFF( created, (
   SELECT MIN( created )
FROM weights
WHERE w.id = weights.id ) ) /7) AS diff
FROM weights AS w
ORDER BY id, diff

此代码不做数据透视表。您应该添加一些额外的代码来将数据转换为您的需要。如果您使用 WEEK() 可能会遇到麻烦,因为这些年。

于 2012-05-07T12:30:35.177 回答