Friday, 17 May 2013

#36 Snake Query

select idcovjob, a.idprod, quantity*hna amount, 2013 year, 4 month, quantity, hna price
    --into #targetbychannel
    from (
        select idcovjob, a.idprod, sum(quantity) quantity
        from mtargetchanneldetail a
        where year=2013 and month=5 and idprod=242
        group by idcovjob, idprod
    ) a
    inner join (
        select a.idprod, hna from mproductprice a
        inner join (
            select idprod, max(startdate) startdate from mproductprice where isdeleted=0 and idprod=242 group by idprod
        ) b on (a.idprod=b.idprod and a.startdate=b.startdate)
    ) b on (a.idprod=b.idprod)
    order by 1