我有4张桌子,最后一张给我带来麻烦。 我希望即使不在我选择的日期,也会出现该id(Tanque)的最后结果。 我正在使用sql manager studio 2008
表CB-LA_Sondagens有:
[CodTurnoAuto]
,[CodAbast]
,[Tanque]
,[PSSID]
,[SondagemEfect]
表CB_CFG_Tanques包含:
[Codigo]
,[PSSID]
,[Descricao]
这是查询:
SELECT
CC.[PssID]
,(SELECT Descricao FROM FGER_Armazens (nolock) as FGA WHERE FGA.Codigo = CC.Armazem) as Armazem
,T.Combustivel
,T.Descricao
,T.Ma_ as Capacidade
,cast(SOND.SondagemEfect as int) as Sondagem
,CBA.Data
FROM [MXPETROL_AB].[dbo].[Config_Comunicacoes] (nolock) as CC
LEFT JOIN [CB_CFG_Tanques] (nolock) as T ON T.PSSID = CC.PssID
LEFT JOIN CB_LA_Sondagens (nolock) as sond ON T.PSSID=sond.pssid and T.Codigo=sond.tanque
LEFT JOIN CB_Abastecimentos (nolock) as CBA ON CBA.CodTurnoAuto=sond.CodTurnoAuto and CBA.CodAbast=sond.CodAbast
WHERE TipoExportacao in (0,1) and CC.PSSID = '509' and CBA.Data>='2016-11-14 00:00:00' and CBA.Data<='2016-11-15 00:00:00'
GROUP BY T.Combustivel,Armazem, CC.PSSID, T.Descricao, T.Ma_, SondagemEfect, CBA.Data
我得到了什么:
我希望桌子的其余部分“Tanque”拥有CB_LA_Sondagens(SondagemEffect)中的最后一条记录。如你所见,我应该有7条记录,但我只有4条记录
答案 0 :(得分:0)
SELECT
PSS, Armazem, Descr,Combustivel, cap, (CASE WHEN sondagemfinal = NULL THEN NULL ELSE MAX(Sondagemfinal) END) as sondagem, (CASE WHEN datafinal = NULL THEN NULL ELSE MAX(datafinal) END) as data
FROM(
SELECT PSS, Armazem,Descr, MAX(capacidade) as cap, (CASE WHEN dataa > 0 THEN MAX(Sondagem) ELSE NULL END) as SondagemFinal, MAX(dataa) as datafinal, Combustivel
FROM(
SELECT
CC.[PssID] as Pss
,(SELECT Descricao FROM FGER_Armazens (nolock) as FGA WHERE FGA.Codigo = CC.Armazem) as Armazem
,T.Descricao as descr
,T.Ma_ as Capacidade
,(SELECT top 1 cast(SondagemFinal as int) from CB_LA_Sondagens (nolock) as CLA INNER JOIN CB_Abastecimentos as CB ON CB.CodTurnoAuto = CLA.CodTurnoAuto AND CB.CodAbast = CLA.CodAbast
where CLA.PSSID = CC.PssID and CLA.Tanque = SOND.Tanque and CB.Data <= '2016-11-15 00:00:00'
order by data desc) as sondagem
,CBA.Data as dataa
,(select Descricao from CB_CFG_Combustiveis as comb where comb.codigo in (
(select combustivel from CB_CFG_Tanques as tanq where tanq.pssid=CC.pssid and tanq.codigo=sond.tanque))) as Combustivel
FROM [MXPETROL_AB].[dbo].[Config_Comunicacoes] (nolock) as CC
INNER JOIN [CB_CFG_Tanques] (nolock) as T ON T.PSSID = CC.PssID
INNER JOIN CB_LA_Sondagens (nolock) as sond ON T.PSSID=sond.pssid and T.Codigo=sond.tanque
LEFT JOIN CB_Abastecimentos (nolock) as CBA ON (CBA.CodTurnoAuto=sond.CodTurnoAuto
AND CBA.CodAbast=sond.CodAbast)
AND CBA.Data>='2016-11-14 00:00:00'
AND CBA.Data<='2016-11-15 00:00:00'
WHERE TipoExportacao in (0,1) and CC.Armazem = '509'
GROUP BY Armazem, CC.PSSID, T.Descricao, T.Ma_, SondagemFinal, CBA.Data, sond.tanque
)Res
GROUP BY PSS, Armazem, Descr, dataa, Combustivel
)res
GROUP BY PSS, Armazem, Descr, cap,Combustivel
ORDER BY Armazem ASC, Combustivel