SQL Server : pivot functionality, need to pivot a table(SQL Server:透视功能,需要透视表)
问题描述
我在 SQL Server 中有以下格式的数据.
I have data in SQL Server in the format below.
-ID ID2 status time
-1384904453 417 stop 2013-11-19 23:40:43.000
-1384900211 417 start 2013-11-19 22:30:06.000
-1384822614 417 stop 2013-11-19 00:56:36.000
-1384813810 417 start 2013-11-18 22:30:06.000
-1384561199 417 stop 2013-11-16 00:19:45.000
-1384554623 417 start 2013-11-15 22:30:06.000
-1384475231 417 stop 2013-11-15 00:26:58.000
-1384468224 417 start 2013-11-14 22:30:06.000
-1384388181 417 stop 2013-11-14 00:16:20.000
-1384381807 417 start 2013-11-13 22:30:06.000
-1384300222 417 stop 2013-11-12 23:50:11.000
-1384295414 417 start 2013-11-12 22:30:06.000
-1384218209 417 stop 2013-11-12 01:03:17.000
-1384209015 417 start 2013-11-11 22:30:06.000
我需要的是能够以以下格式显示数据.
What I need is to be able to show data in the following format.
-ID2 start stop
-417 2013-11-19 22:30:06.000 2013-11-19 23:40:43.000
-417 2013-11-18 22:30:06.000 2013-11-19 00:56:36.000
可以这样做吗?我尝试在 SQL Server 中进行数据透视,但它只返回一条记录.有人可以帮忙吗?
Is it possible to do this? I tried pivot in SQL Server but it only returns one record. Can someone help please?
推荐答案
你可以使用 PIVOT 函数来获取结果,我只需将 row_number() 窗口函数应用于数据,这样你可以为每个 ID2 返回多行:
You can use the PIVOT function to get the result, I would just apply the row_number() windowing function to the data so you can return multiple rows for each ID2:
select id2, start, stop
from
(
select id2, status, time,
row_number() over(partition by status
order by time) seq
from yourtable
) d
pivot
(
max(time)
for status in (start, stop)
) piv
order by start desc;
请参阅 SQL Fiddle with Demo.
您还可以使用带有 CASE 表达式的聚合函数来获得最终结果:
You could also use an aggregate function with a CASE expression to get the final result:
select
id2,
max(case when status = 'start' then time end) start,
max(case when status = 'start' then time end) stop
from
(
select id2, status, time,
row_number() over(partition by status
order by time) seq
from yourtable
) d
group by id2, seq;
参见SQL Fiddle with Demo
这篇关于SQL Server:透视功能,需要透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL Server:透视功能,需要透视表
基础教程推荐
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
