3

我的 sql server 2008 数据库中有下表:

MsgID    TrackerId    MsgContent

  1        123           red    //MsgContent corresponding to colour
  2        123          E2120   //MsgContent corresponding to model
  5        123           sam    //MsgContent corresponding to password
  1        111          orange  //MsgContent corresponding to colour
  2        111          M3420   //MsgContent corresponding to model
  5        111           pam    //MsgContent corresponding to password

我想要一个查询,其结果如下:

TrackerId     Colour    Model    Password   

  123          red      E2120       sam
  111          orange   M3420       pam 

那么,我应该如何解决这个问题呢?提前致谢。

4

4 回答 4

2

您可以通过根据 将表连接到自身TrackerID并过滤来做到这一点MsgID

例子:

SELECT 
     Colour.TrackerId, 
     Colour.MsgContent AS Colour,
     Model.MsgContent AS Model,
     Password.MsgContent AS Password 
FROM MyTable Colour
JOIN MyTable Model ON Colour.TrackerId = Model.TrackerId AND Model.MsgID = 2
JOIN MyTable Password ON Colour.TrackerId = Password.TrackerId AND Password.MsgID = 5
WHERE Colour.MsgID = 1
于 2013-07-24T14:49:46.433 回答
2

这是一个使用PIVOT. 我唯一的问题是不必要的聚合函数。我不知道您的表定义,但如果您只有 MsgID、TrackerID、MsgContent 列,那么选择分组、展开和聚合列进行透视的 CTE 是多余的。如果您确实有更多列,则保留 CTE,否则您将在结果中获得空值。

SELECT TrackerID, [1] [Colour], [2] [Model], [5] [Password]
FROM 
(
  SELECT 
    MsgID, -- spreading column
    TrackerID, -- grouping column
    MsgContent -- aggregation column
  FROM Trackers
) p
PIVOT
(
  MAX(MsgContent)
  FOR MsgID IN( [1], [2], [5] )
) AS pvt

SQLFiddle

您还可以对每种类型的值使用选择。

SELECT DISTINCT TrackerID,
  (SELECT MsgContent FROM trackers t2 
   WHERE t2.MsgID = 1 AND t2.TrackerID = t1.TrackerID) [Colour],
  (SELECT MsgContent FROM trackers t2 
   WHERE t2.MsgID = 2 AND t2.TrackerID = t1.TrackerID) [Model],
  (SELECT MsgContent FROM trackers t2 
   WHERE t2.MsgID = 5 AND t2.TrackerID = t1.TrackerID) [Password]
FROM Trackers t1

SQLFiddle

于 2013-07-24T14:53:26.680 回答
0
Select [TrackerId],[1] AS Color,[2] as Model,[5] AS [Password]
FROM 
    (SELECT [TrackerId], [MsgID], MAX([MsgContent]) as [MsgContent]
    FROM Table1
    GROUP BY [TrackerId], [MsgID]
    )x
    PIVOT
    (
        MAX([MsgContent])
        FOR [MsgID] IN ([1],[2],[5])
    )p

Sql 小提琴

于 2013-07-24T15:04:40.723 回答
0

这是枢轴方法:

select TrackerId, [1] as Colour, [2] as Model, [5] as Password
from Trackers
pivot (max(MsgContent) for MsgId in ([1], [2], [5])) pvt

唯一的技巧是您需要重命名列。这是在select子句中完成的。

编辑:

丹尼尔的评论是正确的。该问题通常使用子查询来解决:

with trackers(MsgId, TrackerId, MsgContent, extra) as (
      select 1, 123, 'red', 0 union all
      select 2, 123, 'E2120', 2 union all
      select 5, 111, 'orange', 8 union all
      select 2, 111, 'M3420', 9 union all
      select 5, 111, 'pam', 10
     ) 
select TrackerId, [1] as Colour, [2] as Model, [5] as Password
from (select MsgId, TrackerId, MsgContent
      from Trackers t
     ) t
pivot (max(MsgContent) for MsgId in ([1], [2], [5])) pvt;
于 2013-07-24T15:02:40.590 回答