SQL数据库从行数据到列

时间:2018-04-03 05:45:47

标签: sql sql-server sql-server-2008

我的数据库中有数据(见下文)

ID  STATUS  date    time
------------------------
223 IN  20180219    658
223 OUT 20180219    1822
223 IN  20180220    711
223 OUT 20180220    1806
223 IN  20180221    710
223 OUT 20180221    2007
223 IN  20180222    709
223 OUT 20180222    1805
223 IN  20180223    711
223 OUT 20180223    1703

我已经使用过group by但我遇到了一个错误。我可以使用什么方法或查询来获取此信息:

ID  date        IN  OUT
--- --------   ---- ----
223 20180219    658 1822
223 20180220    711 1806
223 20180221    710 2007
223 20180222    709 1805
223 20180223    711 1703

4 个答案:

答案 0 :(得分:1)

试试这个:

SELECT ID,date
    ,MAX(CASE WHEN Status = 'IN' THEN time END) IN
    ,MAX(CASE WHEN Status = 'OUT' THEN time END) OUT
GROUP BY ID,date

答案 1 :(得分:1)

请使用PIVOT操作。详情链接如下: https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

答案 2 :(得分:1)

您的问题的解决方案使用动态SQL查询:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Status) 
            FROM Table1 c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT id, date, ' + @cols + ' from 
            (
                select id
                    , Status
                    , date
                    , time
                from Table1
           ) x
            pivot 
            (
                 max(time)
                for Status in (' + @cols + ')
            ) p '

 execute(@query)

<强>输出:

id  date      IN    OUT
223 20180219  658   1822
223 20180220  711   1806
223 20180221  710   2007
223 20180222  709   1805
223 20180223  711   1703

点击演示链接:

  

http://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=edbafbfa0d6b0d210c81fd745d815224

答案 3 :(得分:1)

使用Pivot

;With cte(ID,[STATUS],[date],[time])
AS
(
SELECT 223,'IN' , 20180219, 658  UNION ALL
SELECT 223,'OUT', 20180219, 1822 UNION ALL
SELECT 223,'IN' , 20180220, 711  UNION ALL
SELECT 223,'OUT', 20180220, 1806 UNION ALL
SELECT 223,'IN' , 20180221, 710  UNION ALL
SELECT 223,'OUT', 20180221, 2007 UNION ALL
SELECT 223,'IN' , 20180222, 709  UNION ALL
SELECT 223,'OUT', 20180222, 1805 UNION ALL
SELECT 223,'IN' , 20180223, 711  UNION ALL
SELECT 223,'OUT', 20180223, 1703
)
SELECT ID,[date],[IN],[OUT]
FROM
(
    SELECT * FROM cte
)AS Src
PIVOT
(MAX([time]) FOR [STATUS] IN([IN],[OUT])
)AS pvt

结果

ID  date        IN  OUT
------------------------
223 20180219    658 1822
223 20180220    711 1806
223 20180221    710 2007
223 20180222    709 1805
223 20180223    711 1703