如何在sql中透视临时表

时间:2017-02-27 12:59:40

标签: sql sql-server sql-server-2008 pivot-table

      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

这是一个临时表。我只想将时间列显示为2列,1列显示模式= 3,其他模式= 1。

这是临时表。我只想要以下输出:

          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

3 个答案:

答案 0 :(得分:1)

猜测您想要一种方法来创建具有固定值(1和3)的交替行。 你可以用

ROW_NUMBER()结束时的情况(按[日期]排序)%2 = 0然后1其他3

作为模式列的逻辑

答案 1 :(得分:1)

试试这个,

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

答案 2 :(得分:0)

这有效,具体取决于数据和数据类型/架构(如果表的名称是 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
  
      
  • outerQuery仅选择in-times mode = 3
  •   innerQuery中的
  • 选择与所选时间相对应的下一个输出时间,并且仅返回第一个输出时间。按日期和时间排序,应该是下一个。 仅使用您的给定数据进行测试
  •   

输出

    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

仅供参考:
我使用了这个表模式

 CREATE TABLE timeTable(
     date DATE,
     time TIME,
     mode INTEGER,
     id INTEGER
 );

<强>更新
时差:

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