如何在一行中获取同名的多行数据?

时间:2014-07-24 11:04:45

标签: sql-server-2008 union

SELECT * from (
SELECT 'Rupesh' Name ,'2014-02-27 00:00:00.000' OfficeDate,'9.30' InTime,'' OutTime
UNION
SELECT 'Rupesh' Name,'2014-02-27 00:00:00.000' OfficeDate,'' InTime,'6.30' OutTime
UNION
SELECT 'Rupesh' Name ,'2014-02-26 00:00:00.000' OfficeDate,'11.30' InTime,'' OutTime
UNION
SELECT 'Rupesh' Name ,'2014-02-26 00:00:00.000' OfficeDate,'' InTime,'9.30' OutTime
)p

采样数据:

----------------------------------------------------
Name    |OfficeDate                 |InTime|OutTime
----------------------------------------------------
Rupesh  |   2014-02-26 00:00:00.000 |       |9.30
Rupesh  |   2014-02-26 00:00:00.000 |11.30  |   
Rupesh  |   2014-02-27 00:00:00.000 |       |6.30
Rupesh  |   2014-02-27 00:00:00.000 |9.30   |   
----------------------------------------------------

我想要的结果是以下方式:

Rupesh  2014-02-26 00:00:00.000 11.30   9.30    

Rupesh  2014-02-27 00:00:00.000 9.30    6.30

4 个答案:

答案 0 :(得分:2)

您希望按NameOfficeDate分组并合并InTimeOutTime? 您可以使用以下使用ranking functions的CTE:

WITH CTE AS(
  SELECT Name, OfficeDate, 
         InTimeOld = InTime, OutTimeOld = OutTime,
         InTimeNew = MAX(InTime) OVER(PARTITION BY Name, OfficeDate), 
         OutTimeNew= MAX(OutTime)OVER(PARTITION BY Name, OfficeDate),
         RN = Row_Number() Over (Partition By Name, OfficeDate
                                 Order By Name, OfficeDate, Intime, OutTime)
  FROM dbo.TableName t
)
SELECT Name, OfficeDate, InTime = InTimeNew, OutTime = OutTimeNew
FROM CTE
WHERE RN = 1

Sql-Fiddle

答案 1 :(得分:0)

你可以这样做:

SELECT 
    TABLE1.Name,
    TABLE1.OfficeDate,
    MAX(TABLE1.InTime) AS InTime,
    MAX(TABLE1.OutTime) AS OutTime
FROM TABLE1
GROUP BY
    TABLE1.Name,
    TABLE1.OfficeDate

答案 2 :(得分:0)

谢谢你guyz,但我在这里解决了它的解决方案:

SELECT name, OfficeDate, [InTime] ,[OutTime] from 
 (
    SELECT name,OfficeDate, 'OutTime' status,OutTime Times from #DATA           
    UNION           
    SELECT name,OfficeDate, 'InTime' status, InTime Times from #DATA    
 ) x
pivot 
(
   MAX(Times)
   for status in (InTime,OutTime)
) p 

答案 3 :(得分:-1)

参考Fiddle

SELECT 
    TABLE1.Name,
    TABLE1.OfficeDate,
    MIN(TABLE1.InTime) AS InTime,   -- Minimum Intime
    MAX(TABLE1.OutTime) AS OutTime   --- Maximum Outtime
FROM TableName TABLE1
GROUP BY
    TABLE1.Name,
    TABLE1.OfficeDate;