Quantcast
Channel: SQL Server Integration Services forum
Viewing all articles
Browse latest Browse all 24688

Querying data using partition function

$
0
0

Hi All,

I wrote a query to get data in a particular order but there is some issue because of which i am not

getting desired result.

create table Cat ( Product varchar(10), Loc varchar(10), DDate varchar(40), Price int ) insert into Cat values('A','BN','2015-12-02 00:00:00.000',95) insert into Cat values('A','BN','2015-12-20 00:00:00.000',95) insert into Cat values('A','BN','2016-03-09 00:00:00.000',93) insert into Cat values('A','BN','2016-03-18 00:00:00.000',96) insert into Cat values('A','KL','2015-12-02 00:00:00.000',214) insert into Cat values('A','KL','2015-12-20 00:00:00.000',184) insert into Cat values('A','KL','2016-03-09 00:00:00.000',167) insert into Cat values('A','KL','2016-03-18 00:00:00.000',157)

Please find the images of current output and expected output.

CURRENT O/P:

EXPECTED O/P:

In row number 3 and 4, Rnk should be 1 and 2 instead of 2 and 3.

I wrote the below query to get the desired output but i am not getting the expected output.

select a.Product,a.Loc,b.DDate,a.Mean,b.Price,
case
when b.Price>a.Mean then 'Above'
when b.Price<a.Mean then 'Below'
End,
rank() over(partition by a.Product,a.Loc,

case
when b.Price>a.Mean then 'Above'
when b.Price<a.Mean then 'Below'
End
 order by b.DDate desc) as Rnk


 from Cat b inner join (
select Product,Loc,Avg(Price) as Mean from Cat
group by Product,Loc) a
on a.Product=b.Product and a.Loc=b.Loc

order by a.Product,a.Loc,b.DDate desc

Thanks

Syed



Viewing all articles
Browse latest Browse all 24688

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>