【问题标题】:TSQL: transpose last 3 columns into rows?TSQL:将最后 3 列转置为行?
【发布时间】:2019-07-06 09:05:24
【问题描述】:

一直在尝试各种转置方法,包括枢轴,& 聚合/CASE,但似乎没有任何工作正常。
希望转置最后 3 列(5 列矩阵) 到每个唯一 ID 的行中。下图。

这似乎是一个如此简单的问题。真的应该有 一个简单的解决方案。

谁能指出我正确的方向?

Here is the code to generate the temporary table:

-- -- BEGIN: Clean up temp tables: -- -- -- -- -- -- -- -- -- -- -- -
-- 
-- Remove the temporary table if it exists -- -- -- -- -- -- --
If OBJECT_ID('tempdb..#StrongmanTempTable') is NOT NULL
  BEGIN
  -- PRINT N'Table exists.  Now deleting...';
  DROP TABLE #StrongmanTempTable
  END
-- 
-- --   END: Clean up temp tables: -- -- -- -- -- -- -- -- -- -- -- -

CREATE TABLE #StrongmanTempTable
  (
  EntrantID      INT,
  Entrant        VARCHAR (64),
  Event          VARCHAR (64),
  Judge1Score    float,
  Judge2Score    float,
  )

INSERT INTO #StrongmanTempTable
VALUES
    (1, 'Bluto',    'Tire Flip',    9.0,    9.9),
    (1, 'Bluto',    'Vehicle Pull', 6.3,    9.8),
    (2, 'Mighty Mouse', 'Log Throw',    6.1,    7.7),
    (2, 'Mighty Mouse', 'Tire Flip',    7.2,    9.0),
    (3, 'Popeye',   'Vehicle Pull', 9.0,    8.3),
    (2, 'Mighty Mouse', 'Vehicle Pull', 7.4,    7.8),
    (3, 'Popeye',   'Log Throw',    8.0,    9.7),
    (1, 'Bluto',    'Log Throw',    8.2,    8.3),
    (3, 'Popeye',   'Tire Flip',    6.5,    9.2)



-- For testing:
SELECT * FROM #StrongmanTempTable

【问题讨论】:

    标签: tsql transpose


    【解决方案1】:

    有很多可能的解决方案,但我个人会使用 CTE。要使 CTE 正常工作,您需要在开头包含 ; 以关闭之前的任何语句。

    我假设full outer join 以防万一任何EntrantID 参加了一个活动而不是另一个活动,如果不是这种情况,请根据需要更改join

    ; with log_throw as
        (
            select t.*
            from #StrongmanTempTable as t
            where t.[Event] = 'Log Throw'
        )
        , tire_flip as
        (
            select t.*
            from #StrongmanTempTable as t
            where t.[Event] = 'Tire Flip'
        )
        , vehicle_pull as
        (
            select t.*
            from #StrongmanTempTable as t
            where t.[Event] = 'Vehicle Pull'
        )
    select l.EntrantID
    , l.Entrant
    , l.[Event]
    , l.Judge1Score
    , l.Judge2Score
    , f.[Event]
    , f.Judge1Score
    , f.Judge2Score
    , p.[Event]
    , p.Judge1Score
    , p.Judge2Score
    from log_throw as l
    full outer join tire_flip as f on l.EntrantID = f.EntrantID
    full outer join vehicle_pull as p on l.EntrantID = p.EntrantID
    order by 1
    

    【讨论】:

    • 谢谢,Tarheel——它有效!不幸的是,这只是现实世界问题的一个简单示例。我真正的问题是未知的“事件”,所以我无法将它们硬编码到解决方案中。有没有办法考虑到这一点?
    • 您必须使用动态 SQL。 this 我的其他答案之类的东西是最好的起点。
    猜你喜欢
    • 1970-01-01
    • 2013-03-31
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2016-02-25
    • 1970-01-01
    相关资源
    最近更新 更多