我正在获取重复的数据行。
wh.whsheaderID不同,它对应于特定单位和特定参考(因此我的“重复值”)。然后我有一个不离开的日期时间,然后是THU离开的不同日期时间。
然而,因为有2个不同的wh.whsheaderID对应于相同的单位和相同的参考我得到2行数据,其中NOT出发日期&将填充扫描日期,并在下一行,THU出发日期&扫描时间将被填充。如何将这些信息整理成一行?
SELECT wh.WhsHeaderID,
mu.Number AS Unit ,
m.MovementRef AS Reference ,
(SELECT CASE WHEN COUNT(*) >=2 THEN 'Yes' ELSE 'No' END FROM dbo.whsHeader WHERE RunMovID = m.movementId) AS [Co-Load],
(Select wh.ArrDepDate where wh.localdepotcode = 'NOT') AS [NOT Departure Date],
(Select wh.LastScannedTime where wh.LocalDepotCode = 'NOT') AS [NOT Last Scan] ,
(Select wh.ArrDepDate where wh.LocalDepotCode = 'THU') as [THU Departure Date],
(Select wh.LastScannedTime where wh.LocalDepotCode = 'THU') as [THU Last Scan],
答案 0 :(得分:1)
使用条件聚合:
select
WhsHeaderId = min(wh.WhsHeaderID)
, Unit = mu.Number
, Reference = m.MovementRef
, [Co-Load] = case when count(*) >=2 then 'Yes' else 'No' end
, [NOT Departure Date] = min(case when wh.localdepotcode = 'NOT' then wh.ArrDepDate end)
, [NOT Last Scan] = max(case when wh.localdepotcode = 'NOT' then wh.LastScannedTime end)
, [THU Departure Date] = min(case when wh.localdepotcode = 'THU' then wh.ArrDepDate end)
, [THU Last Scan] = max(case when wh.localdepotcode = 'THU' then wh.LastScannedTime end)
/* , other columns */
from ...
inner join dbo.whsHeader wh
on wh.RunMovID = m.movementId
group by
mu.Number
, m.MovementRef
/* , other non aggregated columns */