我想根据周将多行转换为单行。它应该如下所示。任何人都可以帮助我吗?
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 | | | |
提前致谢。
答案 0 :(得分: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
,但您可以将汇总更改为您想要的内容。
有用的参考资料:
答案 1 :(得分:1)
如果这是一张表,那么
SELECT GROUP_CONCAT(weight) as Weight,
WEEK(Created) as Week
Group by Week(Created)
这将为您提供一行,每行都有周id和逗号分隔的whights
答案 2 :(得分:0)
你不能像这样动态创建字段,但你可以将它们分组。
使用GROUP_CONCAT
通过分隔符提供结果,以后可以分开。
答案 3 :(得分: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(),则可能会遇到麻烦。