从sql查询的结果中删除重复记录

时间:2013-11-27 13:31:54

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

SELECT 
          Distinct  loc.name,             
             loc.latitude, 
             loc.longitude, 
            loc.imageurl,           
             c.userid, 
             c.locationid, 
             c.time,
             (SELECT Count(*)   FROM   tbl_likecheckin  WHERE  checkinid = c.id) AS TOTALCheckin,
            (SELECT Count(*) FROM   tbl_likecheckin  WHERE  userid = 57 AND checkinid =  c.id) As Checkinflag, 
             CONVERT(DECIMAL(16,2),(dbo.Distancebetween(loc.latitude, loc.longitude, 22.302647, 73.190144))) 
             AS 
             Distance 
      FROM   tblcheckin AS C 
             INNER JOIN tbluser AS u 
                     ON c.userid = u.userid 
             INNER JOIN tblgetlocation AS loc 
                     ON c.locationid = loc.venueid 
      WHERE  c.flag = 'C'    
      and   CONVERT(DECIMAL(16,4),(dbo.Distancebetween(loc.latitude, loc.longitude, 22.302647, 73.190144)))<=(select maxdistance from tblDistance)
         ORDER  BY c.time DESC

enter image description here

  • 以下是我上述查询的输出,我已应用不同但是 由于 imageurl
  • 而导致数据重复
  • 那么我怎样才能从结果中删除重复的记录,无论哪个 从结果中删除重复的行。
  • 我只想要一张唱片。我也需要图像。

2 个答案:

答案 0 :(得分:1)

请参阅:http://www.w3schools.com/sql/sql_distinct.asp

Ur在所有列上使用 DISTINCT ,这就是原因。
如果“imageurl”列产生了麻烦,请将其从DISTINCT关键字的范围中删除。

这可能很有用:SQL - Select distinct but return all columns?

此处示例:http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_distinct
运行此查询:

  

SELECT DISTINCT Country,City FROM Customers;

和这一个:

  

按国家/地区从客户分组选择国家/地区,城市;

答案 1 :(得分:1)

如果没有数据可用,很难回答这个问题。左连接应该意味着原始CTE结果集保持不变,并且希望只抓取它发现的第一个图像匹配,保持记录数相同。

with cte as (
SELECT 
Distinct  loc.name,             
loc.latitude, 
loc.longitude, 
c.userid, 
c.locationid, 
c.time,
(SELECT Count(*)   FROM   tbl_likecheckin  WHERE  checkinid = c.id) AS TOTALCheckin,
(SELECT Count(*) FROM   tbl_likecheckin  WHERE  userid = 57 AND checkinid =  c.id) As Checkinflag, 
CONVERT(DECIMAL(16,2),(dbo.Distancebetween(loc.latitude, loc.longitude, 22.302647, 73.190144))) 
AS 
Distance 
FROM   tblcheckin AS C 
INNER JOIN tbluser AS u 
ON c.userid = u.userid 
INNER JOIN tblgetlocation AS loc 
ON c.locationid = loc.venueid 
WHERE  c.flag = 'C'    
and CONVERT(DECIMAL(16,4),(dbo.Distancebetween(loc.latitude, loc.longitude, 22.302647, 73.190144)))<=(select maxdistance from tblDistance)
)
select cte.name, cte.latitude, cte.longitude, cte.userid, cte.locationid, cte.[time], cte.Distance, imagetable.imageurl
from cte
left outer join (SELECT 
Distinct 
loc.name,
loc.imageurl,
FROM   tblcheckin AS C 
INNER JOIN tbluser AS u 
ON c.userid = u.userid 
INNER JOIN tblgetlocation AS loc 
ON c.locationid = loc.venueid 
WHERE  c.flag = 'C'    
and CONVERT(DECIMAL(16,4),(dbo.Distancebetween(loc.latitude, loc.longitude, 22.302647, 73.190144)))<=(select maxdistance from tblDistance)) imagetable
on cte.name = imagetable.name