我有以下SQL代码:
SELECT TOP (1000)
a.[JourneyNumber]
,a.[JourneyDate]
,a.[tReg_ID]
,a.[Reg]
,a.[ID]
,b.tLocationPosition_ID
,c.LifeCode
,c.LifeTotal
,CASE WHEN c.LifeCode LIKE 'LCF1' AND b.tLocationPosition_ID = 1 THEN c.LifeTotal END as ALCF1
,CASE WHEN c.LifeCode LIKE 'LCF1' AND b.tLocationPosition_ID = 2 THEN c.LifeTotal END as BLCF1
FROM [RALNHVTST].[dbo].[tRegJourney] as a
LEFT JOIN [RALNHVTST].[dbo].[tRegJourneyLogBook] as b
ON a.ID = b.tRegJourney_ID
LEFT JOIN [RALNHVTST].[dbo].[tRegJourneyLogBookLifeCodeEvents] AS c
ON b.ID = c.tRegJourneyLogBook_ID
WHERE b.tLocation_ID = 720
AND a.tReg_ID = 73 OR a.tReg_ID = 38
AND (b.tLocationPosition_ID = 1 OR b.tLocationPosition_ID = 2)
AND (c.LifeCode LIKE 'LCF1' )
ORDER BY JourneyDate
在SELECt语句中,我试图将主要包含相同信息的多行转换为列。
所以这样:
JourneyNo JourneyDate Reg ID tLocationPos_ID LifeCodeLifeTotal
4A 2015-08-31 00:00:00.000 OO-NSN 45023 1 LCF1 68.0000
4A 2015-08-31 00:00:00.000 OO-NSN 45023 2 LCF1 67.0000
成为此:
JourneyNumber JourneyDate Reg ID LifeCode ALCF1 BLCF1
4A 2015-08-31 00:00:00.000 OO-NSN 45023 LCF1 68.0000 67.000
但是我却得到了这个:
JourneyNumber JourneyDate Reg ID LifeCode ALCF1 BLCF1
4A 2015-08-31 00:00:00.000 OO-NSN 45023 LCF1 68.0000 NULL
4A 2015-08-31 00:00:00.000 OO-NSN 45023 LCF1 NULL 67.0000
有人可以帮我解决这个问题吗?
谢谢!
使用汇总
SELECT TOP (1000)
a.[JourneyNumber]
,a.[JourneyDate]
,a.[tReg_ID]
,a.[Reg]
,a.[ID]
,b.tLocationPosition_ID
,c.LifeCode
,c.LifeTotal
,max(CASE WHEN c.LifeCode LIKE 'LCF1' AND b.tLocationPosition_ID = 1 THEN c.LifeTotal END) as ALCF1
,max(CASE WHEN c.LifeCode LIKE 'LCF1' AND b.tLocationPosition_ID = 2 THEN c.LifeTotal END) as BLCF1
FROM [RALNHVTST].[dbo].[tRegJourney] as a
LEFT JOIN [RALNHVTST].[dbo].[tRegJourneyLogBook] as b
ON a.ID = b.tRegJourney_ID
LEFT JOIN [RALNHVTST].[dbo].[tRegJourneyLogBookLifeCodeEvents] AS c
ON b.ID = c.tRegJourneyLogBook_ID
WHERE b.tLocation_ID = 720
AND a.tReg_ID = 73 OR a.tReg_ID = 38
AND (b.tLocationPosition_ID = 1 OR b.tLocationPosition_ID = 2)
AND (c.LifeCode LIKE 'LCF1' )
group by a.[JourneyNumber]
,a.[JourneyDate]
,a.[tReg_ID]
,a.[Reg]
,a.[ID]
,b.tLocationPosition_ID
,c.LifeCode
,c.LifeTotal
ORDER BY JourneyDate