SQL查询提供了多个重复数据

时间:2013-08-16 14:50:39

标签: sql

此查询出了什么问题;它给了我不止一个重复的数据行

select (SELECT TOP(1) balanceaccount
        FROM balanceaccountmovement
        WHERE balanceaccount.CId = cr.CId 
        ORDER BY Date DESC) as kk,
        balanceaccountmovement.CId
from Customer cr 
join balanceaccountmovement
on cr.CId = balanceaccountmovement.CId
where kk > 0

3 个答案:

答案 0 :(得分:2)

我认为它是SQL Server,因为你使用了TOP(1):

SELECT bam.balanceaccount, bam.CId
FROM Customer cr 
JOIN balanceaccountmovement bam ON bam.CId = cr.id
     AND bam.balanceaccount > 0
     AND Date = (SELECT TOP(1) date 
                 FROM balanceaccountmovement bam2 
                 WHERE bam.CId = bam2.CId
                 ORDER BY date DESC)

SQLFIDDLE:http://www.sqlfiddle.com/#!3/6a2bec/2/0

答案 1 :(得分:0)

您可以分享有关数据的更多信息吗?

只是查看查询,我认为这是一个" Group By"会有所帮助。

另外,你只做一个" SELECT TOP(1)"对于子查询。您也可以为包含SELECT的内容执行此操作。

希望有所帮助。

答案 2 :(得分:0)

Select (SELECT TOP(1) CariBakiye   FROM 
                        CariHesapHareketleri 
                    where   CId= cr.CId ORDER BY Trh DESC

                     ) as kk,    CariHesapHareketleri.CId  from
                    Cari cr 

看到你是选择Top(1) cariBakiye但是CId怎么样? 那么看看这种方式尝试只执行这么多的查询(删除连接和别名后),你会得到重复的CariBakiye和所有Cid值

Something like this

所以你的查询错了。 你能否详细说明你的要求。


select TOP(1) (SELECT TOP(1) CariBakiye   FROM 
                        CariHesapHareketleri 
                    where   CId= cr.CId ORDER BY Trh DESC

                     ) as kk,    CariHesapHareketleri.CId  from
                    Cari cr 
                    join CariHesapHareketleri   on cr.CId=CariHesapHareketleri.CId
                 where kk > 0  

select balanceaccount,(SELECT TOP(1) balanceaccount
        FROM balanceaccountmovement
        WHERE balanceaccount.CId = cr.CId 
        ORDER BY Date DESC) as kk,
        balanceaccountmovement.CId
from Customer cr 
join balanceaccountmovement
on cr.CId = balanceaccountmovement.CId
where kk > 0

试试这个,你会发现你没有收到重复的数据,但sql如何将这些数据重新分配给你?因此,在主查询中也使用TOP子句。

- 希望我的方向正确。如果不是,请让我知道