[英]How to pivot temp table in sql
Date Time Mode ID
2017-01-01 13:00:00.0000000 3 10
2017-01-01 14:00:00.0000000 1 10
2017-01-01 15:00:00.0000000 3 10
2017-01-01 15:30:00.0000000 1 10
This is a temp table.I just want to display time column as 2 columns,1 column with mode =3 and other with mode=1. 这是一个临时表。我只想将时间列显示为2列,模式= 3时显示1列,而模式= 1时显示其他列。
This is a temp table.I just want the below output: 这是一个临时表,我只想要以下输出:
Date InTime(Mode-3) OutTime(Mode-1) ID
2017-01-01 13:00:00.0000000 14:00:00.0000000 10
2017-01-01 15:00:00.0000000 15:30:00.0000000 10
Guessing you want a method to create alternating rows with fixed values (1 and 3). 猜测您想要一种方法来创建具有固定值(1和3)的交替行。 you can use 您可以使用
case when ROW_NUMBER() over (order by [Date])%2 = 0 then 1 else 3 ROW_NUMBER()超过(按[日期]排序)%2 = 0然后1否则3的情况
as the logic for your mode column 作为模式列的逻辑
Try this, 尝试这个,
DECLARE @TB TABLE (DATETIME VARCHAR(30),ID INT)
INSERT INTO @TB VALUES
('2017-01-01 13:00:00.0000000',10),
('2017-01-01 14:00:00.0000000',10),
('2017-01-01 15:00:00.0000000',10),
('2017-01-01 15:30:00.0000000',10 )
SELECT SUBSTRING(DATETIME,0,11) DATE
,SUBSTRING(DATETIME,12,LEN(DATETIME)) TIME
,CASE WHEN ROW_NUMBER() OVER (ORDER BY DATETIME)%2 = 0 THEN 1 ELSE 3 END MODE
,ID
FROM @TB
This works, depending on the data and datatypes/schema (and if the name of the table is timeTable ): 这有效,取决于数据和数据类型/模式(以及表的名称是否为timeTable ):
SELECT DATE, time AS 'InTime(Mode-3)',
(SELECT TOP 1 time FROM timeTable
WHERE mode = 1
AND id = outerTable.id
AND date = outerTable.date
AND time > outerTable.time
ORDER BY date, time) AS 'OutTime(Mode-1)',
ID
FROM timeTable AS outerTable
WHERE mode = 3
- the outerQuery only selects the in-times mode = 3 outsideQuery仅选择即时模式= 3
- in innerQuery selects the next out-time, that correspondes to the selected in-time, and only returns the first one. 在innerQuery中选择与选择的时间对应的下一个时间,仅返回第一个时间。 since ordered by date and time, it should be the next one. 由于按日期和时间排序,因此应该是下一个。 Only tested with your given data 仅使用给定数据进行测试
Output: 输出:
Date | InTime(Mode-3) | OutTime(Mode-1) | ID
---------------|---------------------|---------------------|------
2017-01-01 | 13:00:00.0000000 | 14:00:00.0000000 | 10
2017-01-01 | 15:00:00.0000000 | 15:30:00.0000000 | 10
Just for reference: 仅供参考:
I used this table schema 我使用了这个表模式
CREATE TABLE timeTable(
date DATE,
time TIME,
mode INTEGER,
id INTEGER
);
Update: 更新:
With time - difference: 随时间-差异:
SELECT *, DATEDIFF(MINUTE,INTIME,OUTTIME) AS [DIFFERENCE] FROM (
SELECT [DATE], [time] AS INTIME,
(SELECT TOP 1 [time] FROM timeTable
WHERE [mode] = 1
AND [id] = outerTable.id
AND [date] = outerTable.date
AND [time] > outerTable.time
ORDER BY [date], [time]) AS OUTTIME,
[ID]
FROM [timeTable] AS outerTable
WHERE [mode] = 3
) WholeData
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.