Question

In the query

cr is customers, chh? ise customer_pays, cari_kod is customer code, cari_unvan1 is customer name cha_tarihi is date of pay, cha_meblag is pay amount

The purpose of query, the get the specisified list of customers and their last date for pay and amount of money...

Actually my manager needs more details but the query is very slow and that is why im using only 3 subquery.

The question is how to combine them ?

I have researched about Cte and "with clause" and "subquery in "where " but without luck.

Can anybody have a proposal.

Operating system is win2003 and sql server version is mssql 2005.

Regards


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
Was it helpful?

Solution

You will probably speed up the query by changing your last where clause to:

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

Assuming that you want both the date condition met and one of the two codes. Your original logic is the (date and code = 322) OR (code = 324).

The overall query can be improved by finding the record in the chh table and then just using that. For this, you want to use the window function row_number(). I think this is the query that you want:

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;

This version assumes the revised logic date/code logic.

The inner subquery select might generate an error if there are two columns with the same name in both tables. If so, then just list the columns instead of using *.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top