如何将行的值展现到列里?

我很不要脸的来当伸手党了,但是实在卡了一会,我有如下这个表:

+----+--------+--------+-------+
| id | name   | date   | Income |
+----+--------+--------+-------+
|  1 | tom    | 20210331 | 100   |
|  2 | tom    | 20210330 | 200   | 
|  3 | james  | 20210331 | 30    |
|  4 | james  | 20210330 | 90    |
+----+--------+--------+-------+ 

想获得这样的结果,能体现出来对比:

+----+--------+---------+-------------+----------+----------------+
| id | name   | today   | todayIncome |yesterday | yesterdayIncome| 
+----+--------+---------+-------------+----------+----------------+
|  1 | tom    | 20210331| 100         | 20210330 | 200            | 
+----+--------+---------+-------------+----------+----------------+ 
|  2 | james  | 20210331| 30          | 20210330 | 90             | 
+----+--------+---------+-------------+----------+----------------+ 

请问这样的mysql语句怎么写... 先跪谢了...

阅读 1.3k
1 个回答

大概是一条这样的 SQL?

SELECT 
n1.id, n1.name, 
n1.date as today, n1.income as todayIncome,
n2.date as yesterday, n2.income as yesterdayIncome
FROM NewTable1 n1, NewTable1 n2
where DATEDIFF(n1.date, n2.date) = 1
and n1.name = n2.name
and n1.date > n2.date 

datadiff(...) 函数来让日期跨度为1天。

idnametodaytodayIncomeyesterdayyesterdayIncome
2tom2021-03-31100.02021-03-30200.0
5tom2021-04-01150.02021-03-31100.0
4james2021-03-3130.02021-03-3090.0
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题