-2

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

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
4

3 回答 3

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

于 2013-08-16T15:46:37.010 回答
0

你能分享更多关于你的数据吗?

只看查询,我认为“分组依据”会有所帮助。

此外,您只为子查询执行“SELECT TOP(1)”。您可能还想对包含的 SELECT 执行此操作。

希望有帮助。

于 2013-08-16T15:03:26.707 回答
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 和 All Cid 值

像这样的东西

所以你的查询在这里是错误的。你能详细说明你的要求吗?


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在你的主查询中也使用子句。

- 希望我的方向是正确的。如果不是,请告诉我

于 2013-08-16T15:04:12.577 回答