区别在于sql中只有一列

时间:2014-06-04 16:26:36

标签: sql

我有一个查询,我希望只在一列中有所不同 - InjuryScenario.id,现在它要求出错 - 如何使用此查询执行此操作:

SELECT TOP (10) 
    Cause.Cause_name, 
    City.City_name, 
    distinct InjuryScenario.InjuryScenario_id,
    InjuryScenario.Date, 
    Place.Place_name, 
    Media.Media_name, 
    InjuryScenario.InjuryDesc, 
    Media.MediaType_name 
FROM InjuryScenario 
INNER JOIN Cause 
    ON InjuryScenario.Cause_id = Cause.Cause_id 
INNER JOIN PlaceDet 
    ON InjuryScenario.InjuryScenario_id = PlaceDet.InjuryScenario_id 
INNER JOIN City 
    ON PlaceDet.City_id = City.City_id 
INNER JOIN Place 
    ON InjuryScenario.Place_id = Place.Place_id 
INNER JOIN Media2InjuryScenario 
    ON InjuryScenario.InjuryScenario_id = Media2InjuryScenario.InjuryScenario_id 
INNER JOIN Media 
    ON Media2InjuryScenario.Media_id = Media.Media_id 
ORDER BY InjuryScenario.TimeStamp DESC

谢谢

1 个答案:

答案 0 :(得分:-1)

SELECT DISTINCT 是一个关键字,您无法将其分开

您很可能在连接表之间存在一对多关系。您的第一步是找到哪一个,然后可能执行 Row_Number() 将其划分为列,然后选择您想要的

假设 PlaceDet InjuryScenario 的多对一,并且您只希望先加入在PlaceDet中记录(如果按日期排序),则

您的代码看起来像这样

SELECT TOP (10) 
    Cause.Cause_name, 
    City.City_name, 
    InjuryScenario.InjuryScenario_id,
    InjuryScenario.Date, 
    Place.Place_name, 
    Media.Media_name, 
    InjuryScenario.InjuryDesc, 
    Media.MediaType_name 
FROM InjuryScenario 
INNER JOIN Cause ON InjuryScenario.Cause_id = Cause.Cause_id 
INNER JOIN (SELECT InjuryScenario_id, ROW_NUMBER() OVER(PARTITION BY InjuryScenario_id ORDER BY InjuryDate ASC) AS RowRank FROM PlaceDet) PlaceDet ON (InjuryScenario.InjuryScenario_id = PlaceDet.InjuryScenario_id AND PlaceDet.RowRank = 1)
INNER JOIN City ON PlaceDet.City_id = City.City_id 
INNER JOIN Place ON InjuryScenario.Place_id = Place.Place_id 
INNER JOIN Media2InjuryScenario ON InjuryScenario.InjuryScenario_id = Media2InjuryScenario.InjuryScenario_id 
INNER JOIN Media  ON Media2InjuryScenario.Media_id = Media.Media_id 
ORDER BY InjuryScenario.TimeStamp DESC