如何组合此查询

时间:2013-05-17 13:07:06

标签: sql sql-server-2005 subquery master-detail sql-subselect

在查询中

cr是客户, CHH? ise customer_pays, cari_kod是客户代码, cari_unvan1是客户名称 cha_tarihi是工资日期, cha_meblag是支付金额

查询的目的,获取具体的客户名单及其最后的付款日期和金额......

实际上我的经理需要更多细节,但查询速度非常慢,这就是我只使用3个子查询的原因。

问题是如何将它们结合起来?

我研究过Cte和“with clause”以及“subquery in”,其中“但没有运气。”

任何人都可以提出建议。

操作系统是win2003,sql server版本是mssql 2005。

此致


select cr.cari_kod,cr.cari_unvan1, cr.cari_temsilci_kodu,
(select top 1
   chh1.cha_tarihi 
   from dbo.CARI_HESAP_HAREKETLERI chh1 where chh1.cha_kod=cr.cari_kod order by chh1.cha_RECno) as sontar,
(select top 1
   chh2.cha_meblag 
   from dbo.CARI_HESAP_HAREKETLERI chh2 where chh2.cha_kod=cr.cari_kod order by chh2.cha_RECno) as sontutar

from dbo.CARI_HESAPLAR cr
where (select top 1
   chh3.cha_tarihi 
   from dbo.CARI_HESAP_HAREKETLERI chh3 where chh3.cha_kod=cr.cari_kod order by chh3.cha_RECno) >'20130314'
and
 cr.cari_bolge_kodu='322'
 or 
 cr.cari_bolge_kodu='324' 
order by cr.cari_kod

1 个答案:

答案 0 :(得分:1)

您可能会通过将上一个where子句更改为:

来加快查询速度
where (select top 1 chh3.cha_tarihi 
       from dbo.CARI_HESAP_HAREKETLERI chh3 where chh3.cha_kod=cr.cari_kod
       order by chh3.cha_RECno
      ) >'20130314' and
      cr.cari_bolge_kodu in ('322', '324')
order by cr.cari_kod

假设您希望满足日期条件和两个代码之一。您的原始逻辑是(日期和代码= 322)OR(代码= 324)。

可以通过查找chh表中的记录然后使用它来改进整体查询。为此,您希望使用窗口函数row_number()。我认为这是您想要的查询:

select cari_kod, cari_unvan1, cari_temsilci_kodu,
       cha_tarihi, cha_meblag
from (select cr.*, chh.*,
             ROW_NUMBER() over (partition by chh.cha_kod order by chh.cha_recno) as seqnum
      from dbo.CARI_HESAPLAR cr join
           dbo.CARI_HESAP_HAREKETLERI chh
           on chh.cha_kod=cr.cari_kod
      where cr.cari_bolge_kodu in ('322', '324')
     ) t
where chh3.cha_tarihi > '20130314' and seqnum = 1
order by cr.cari_kod;

此版本假定修订的逻辑日期/代码逻辑。

如果两个表中有两个具有相同名称的列,则内部子查询选择可能会生成错误。如果是这样,那么只需列出列而不是使用*