Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
SQL
CREATE TABLE dim.SaleTable
([Year] INTEGER,
Country VARCHAR(50),
Province VARCHAR(50),
Sales INTEGER
);

INSERT INTO dim.SaleTable([year],Country,Province,Sales)
VALUES (2008,'USA','NJ',10000),
	(2008,'INDIA','DELHI',5000),
	(2008,'USA','WA',40000),
	(2008,'CHINA','Beijing',10000),
	(2009,'CHINA','Shanghai',30000),
	(2009,'UK','London',10000),
	(2009,'INDIA','TamilNadu',20000),
	(2009,'USA','NJ',30000),
	(2010,'UK','London',60000),
	(2011,'CHINA','Beijing',70000),
	(2011,'INDIA','Delhi',80000),
	(2011,'FRANCE','Mende',50000),
	(2011,'USA','NY',60000)<pre lang="SQL">




This is the table and I want to get min and max sales with max sales province and min sales province from this table. I can get max and min sales but for min value of state and max sales of state I am not getting.

SQL
SELECT Rank1,MAX(Sales) AS MAXSales,MIN(Sales) AS MinSales,Country
FROM (SELECT Country, Province,sales,RANK() OVER (ORDER BY Country) AS Rank1 FROM dim.SaleTable GROUP BY Country,Province,Sales)d
GRoup BY Rank1,Country


Country MaxSales MaxSaleprovince MinSales MinSaleprovince
======= ======== =============== ========= ===============
CHINA 70000 beiging 10000 beijing
India 80000 delhi 20000 tamilnadu
Posted
Updated 14-Oct-15 20:19pm
v4
Comments
ZurdoDev 14-Oct-15 19:49pm    
If you can get for state, why can't you get for province?
Nandhini Devi 14-Oct-15 21:27pm    
I am not getting max sale for province .
ZurdoDev 15-Oct-15 7:05am    
Why? You didn't answer my question.
[no name] 15-Oct-15 1:24am    
Do you need output like below format. Please confirm:

Province MAX Sales MIN Sales
-------- ---------- ----------
Beijing 70000 10000
Delhi 80000 5000
Nandhini Devi 15-Oct-15 1:41am    
Country MaxSales MaxSaleprovince MinSales MinSaleprovince
======= ======== =============== ========= ===============
CHINA 70000 beiging 10000 beijing
India 80000 delhi 20000 tamilnadu

1 solution

Here is what I came up with:
SQL
WITH cte1 AS (
    SELECT s.Country, s.Province, s.Sales
    , ROW_NUMBER() OVER(PARTITION BY s.Country ORDER BY s.Sales) AS RMX
    , ROW_NUMBER() OVER(PARTITION BY s.Country ORDER BY s.Sales DESC) AS RMN
    from #SaleTable s
)
SELECT c1.Country, 
    c1.Province AS ProvinceMin, c1.Sales AS SalesMin, 
    c2.Province AS ProvinceMax, c2.Sales AS SalesMax
from cte1 c1
INNER JOIN cte1 c2 ON c1.Country = c2.Country AND c2.RMX = 1
WHERE c1.RMN = 1;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900