1

I know there are a lot of Pivot table examples on the internet, however I'm new to SQL and I'm having a bit of trouble as all the examples seem to be pertaining to aggregate functions.

Table 1:

|Date         | Tag  |Value |
|06/10 2:00pm |  A   |  65  | 
|06/10 2:00pm |  B   |  44  |
|06/10 2:00pm |  C   |  33  |
|06/10 2:02pm |  A   |  12  |
|06/10 2:02pm |  B   |  55  |
|06/10 2:02pm |  C   |  21  |
....
|06/10 1:58am |  A   |  23  |

What I would like it to look like is (table 2):

|Date        |  A  |  B  |  C  |
|06/10 2:00pm|  65 |  44 |  33 | 
|06/10 2:02pm|  12 |  55 |  21 | 
.....
|06/10 1:58am| 23 | etc.  | etc. |

(sorry for the format)

Some problems that encounter (doesn't work with code I have found online) I'd like to run this as a stored procedure (rather a SQL job), every 2 minutes so that this data from table 1 is constantly being moved to table 2. However I think I would need to alter the date every single time? (thats the syntax I've seen) The pivot table itself seems simple on its own, but the datetime has been causing me grief. Any code snipets or links would be greatly appreciated.

Thanks.

4

1 回答 1

0

枢轴本身似乎很简单:

select *
from table1
pivot (min (Value) for Tag in ([A], [B], [C])) p

至于存储过程,我将使用 table2 中保存的最后日期作为 table1 的过滤器,不包括不完整的组(我假设在某些时候会出现所有三个标签,并且只有最后一个日期可能是不完整的。如果没有,您将需要对最后日期进行特殊处理以更新/插入一行)。

所以,在代码中:

create proc InsertPivotedTags
as
    set NoCount ON
    set XACT_ABORT ON

    begin transaction

    declare @startDate datetime
    -- Last date from Table2 or start of time
    select @startDate = isnull (max ([Date]), '1753-01-01')
      from Table2

    insert into Table2
    select *
      from Table1
     pivot (min (Value) for Tag in ([A], [B], [C])) p
     where [Date] > @startDate
     -- exclude incomplete groups
       and a is not null
       and b is not null
       and c is not null

    commit transaction

如果组可能不完整,您应该删除排除过滤器并添加删除语句以删除最后日期,以防它不完整,并调整@startDate到三毫秒前再次获得相同的行,但现在处于更多填充状态。

于 2012-07-09T23:57:10.290 回答