Table Product
PID(PK)Name
1Mobile
2Laptop
3Fashion
Table Coupons
IDPIDCity
12Bangalore
23Pune
3 2Mumbai
41Bangalore
52Mumbai
I want to select distinct City name records joining two tables
(if i have five different city then its one one record from each city).
Pl'z suggest me, how can i fetch this records.
I trired using distinct keyword to fetch records but i am unable to find desire output....
Hemant SrivastavaPosted Jan 16, 2013, 11:06 AM
SELECT DISTINCT C.City, C.PID, P.Name
FROM Product AS P
INNER JOIN Coupons AS C ON C.PID = P.PID
ORDER BY C.City
____________________________________
City PID Name
____________________________________
Banglore 1 Mobile
Banglore 2 Laptop
Mumbai 2 Laptop
Pune 3 Fashion
So, in this way you get rid of the one duplicate row "Mumbai 2 Laptop" in comparison to previous result.
You can't get rid of Banglore column duplicacy because full row wise "Banglore 1 Mobile" and "Banglore 1 Laptop" are different.
As Jignesh said "Distinct can not be applied to only few columns it is always applied to whole column set means all column which are used with "select"."
Hope it would help you.
Sumit Kumar SinhaPosted Jan 16, 2013, 12:25 AM
Eg:
City PID Product
Bangalore 2 Laptop
Jignesh TrivediPosted Jan 15, 2013, 10:53 PM
The SQL DISTINCT clause allows you to remove duplicates from the result set. The SQL DISTINCT clause can only be used with SQL SELECT statements.
so Distinct can not be applied to only few columns it is always applied to whole column set means all column which are used with "select".
try following two query, it return different result set.
select Distinct City,P.Name from #product p
join #Coupons c on c.PID = p.PID
select Distinct * from #product p
join #Coupons c on c.PID = p.PID
hope this will help you.
Hemant SrivastavaPosted Jan 15, 2013, 5:58 PM
If you use following query:
SELECT C.City, C.PID, P.Name
FROM Product AS P
INNER JOIN Coupons AS C ON C.PID = P.PID
ORDER BY C.City
you would get result as;
__________________________________
City PID Name
__________________________________
Banglore 2 Laptop
Banglore 1 Mobile
Mumbai 2 Laptop
Mumbai 2 Laptop
Pune 3 Fashion
Now what you want?
Anurag SarkarPosted Jan 15, 2013, 1:28 PM
Sumit Kumar SinhaPosted Jan 15, 2013, 9:46 AM
Anurag SarkarPosted Jan 15, 2013, 7:22 AM
and if you want the query please show me the output show that i can make the query for you.