简体   繁体   English

SQL查询:在第1和第2日期之前进行数据透视

[英]SQL query: pivot data by 1st and 2nd date

I have this table in Microsoft SQL Server: 我在Microsoft SQL Server中有此表:

 Id   Date   Value
 111  1/1/19 1
 111  2/1/19 2
 222  5/1/19 4
 222  4/1/19 3 

Is there a way I can rearrange the data into something like this: 有没有一种方法可以将数据重新排列成如下所示:

 Id   OldDate  NewDate  OldValue NewValue
 111  1/1/19   1/2/19   1        2
 222  4/1/19   5/1/19   3        4

Use lag() : 使用lag()

select t.*
from (select t.*,
             lag(date) over (partition by id order by date) as prev_date,
             lag(value) over (partition by id order by date) as prev_value
      from t
     ) t
where prev_date is not null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 T-sql运行第一个查询,然后执行CASE第二个查询并输出数据或“否” - T-sql run 1st query and then CASE 2nd query and output data or 'No' SQL连接2个表,从第2个条件查询第1个表 - SQL join 2 tables, query 1st with condition from 2nd SQL查询与第一和第二最高薪水有关 - Sql query related to 1st and 2nd highest salary SQL第一个列表中的第二个 - SQL any of 1st list IN 2nd SQL 除运算符和 CTE 选择第一个查询中的所有项目但不在第二个查询中 - SQL Except Operator and with CTE to select all the items in 1st query but not in 2nd Query 需要SQL查询帮助-第一个表中的多行应与第二个表中的多个表匹配 - SQL Query help needed - Multiple rows in 1st table should match to multiple table in 2nd table SQL查询根据第一个表的输入从第二个表中获取字段 - SQL query to get fields from 2nd table based on input from 1st oracle 查询只上报上半年或下半年的数据 - oracle query to report data only for the 1st or 2nd half of the year 双倍增量,其中第二增量在遇到数据时在SQL中反映第一 - Double increment where 2nd increment reflects 1st in sql for encounter data 仅存在表的第一个数据库中的第二个数据库中的sql更新数据 - sql update data in 2nd db from 1st db only where table exists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM