在我的SQL查询中获取重复的行

时间:2016-10-05 10:18:48

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

我遇到一个非常奇怪的问题,我运行了一个类似的查询:

SELECT pif.Lat, pif.Lon, pif.IdPlaya, pif.NombrePlaya, ipm.marm, ipm.mart, ipm.marn,
       ipm.dirm, ipm.dirt, ipm.dirn, ipv.velmax_m, ipv.velmax_t, ipv.velmax_n,
       ipp.tmax, ipp.simbm, ipp.simbt, ipp.simbn,ipm.diaprev
FROM   meteo.dbo.SYS_PLATGES_INFO_FULL_TEMP Pif,
       meteo.dbo.in_previsio_poblacio Ipp,
       meteo.dbo.sys_platges_detall Spd,
       meteo.dbo.in_previsio_mars Ipm,
       meteo.dbo.in_previsio_vents Ipv
WHERE  Ipp.idpob = Pif.IdPoblacion
       AND Ipp.diaprev = '05-10-2016 0:00:00'
       AND Spd.IdCiutat = Pif.IdPoblacion
       AND Ipm.id = Spd.IdCosta
       AND Ipm.diaprev = '05-10-2016 0:00:00'
       AND Ipv.id_previsio = Pif.IdPoblacion
       AND Ipv.data_previsio = '05-10-2016 0:00:00'
GROUP BY pif.NombrePlaya,pif.Lat,pif.Lon,pif.IdPlaya,ipm.marm,ipm.mart,ipm.marn
      ipm.dirm,ipm.dirt,ipm.dirn,ipv.velmax_m,ipv.velmax_t,ipv.velmax_n,ipp.idpob,
      ipp.tmax,ipp.simbm,ipp.simbt,ipp.simbn,ipm.diaprev

对于某些表,有一个重复的表:

query result

看看Del Torres,如果你提到这两者之间存在差异(NE / SE)。所以我去了为该列提供数据的表,并在meteo.dbo.in_previsio_mars中搜索了地点ID的记录,但同一日期只存在一条记录,但在运行查询后,有2条日期记录,并且有没有其他记录包含

  

NE E SE

如果你有相同的经验,如果你与我分享,我将不胜感激。

更新1:

表格结构 enter image description here

1 个答案:

答案 0 :(得分:1)

如果您的in_previsio_mars表中有SYS_PLATGES_INFO_FULL_TEMP表的链接,请将其添加到WHERE(JOIN)条件中,就像您使用其他表格in_previsio_vents

一样

事实上:

你有:

AND Ipv.id_previsio = Pif.IdPoblacion

如果可以,请添加:

AND Ipm.id_previsio = Pif.IdPoblacion

最后,我建议你使用一个明确的JOIN表示法如下:

SELECT 
    pif.Lat, pif.Lon, pif.IdPlaya, pif.NombrePlaya,
    ipm.marm, ipm.mart, ipm.marn,
    ipm.dirm, ipm.dirt, ipm.dirn, ipv.velmax_m, ipv.velmax_t, ipv.velmax_n,
    ipp.tmax, ipp.simbm, ipp.simbt, ipp.simbn,ipm.diaprev
FROM meteo.dbo.SYS_PLATGES_INFO_FULL_TEMP Pif
   JOIN meteo.dbo.in_previsio_poblacio Ipp
       ON Ipp.idpob = Pif.IdPoblacion
   JOIN meteo.dbo.sys_platges_detall Spd
       ON Spd.IdCiutat = Pif.IdPoblacion
   JOIN meteo.dbo.in_previsio_mars Ipm
       ON Ipm.id = Spd.IdCosta
       AND Ipm.id_previsio = Pif.IdPoblacion
   JOIN meteo.dbo.in_previsio_vents Ipv
       ON Ipv.id_previsio = Pif.IdPoblacion
WHERE Ipp.diaprev = '05-10-2016 0:00:00'
   AND Ipm.diaprev = '05-10-2016 0:00:00'
   AND Ipv.data_previsio = '05-10-2016 0:00:00'
GROUP BY
    Pif.NombrePlaya,Pif.Lat,Pif.Lon,Pif.IdPlaya,Ipm.marm,
    Ipm.mart,Ipm.marn,Ipm.dirm,Ipm.dirt,Ipm.dirn,Ipv.velmax_m,
    Ipv.velmax_t,Ipv.velmax_n,Ipp.idpob,Ipp.tmax,Ipp.simbm,Ipp.simbt,
    Ipp.simbn,Ipm.diaprev

通过这种方式,您可以控制JOIN条件和WHERE条件(在INNER JOIN中可以相同,但如果使用OUTER JOIN意义更改)