July 26, 2010 at 12:04 am
Hi,
I am using this query now..
Select distinct A, B from Table
And I am getting this result-
AB
A1B1
A2B1
A1B2
A2B2
Its OK, because it is giving me the distinct set of A and B.
What should I do if I just want distinct set of A (I want B to also display).
My final output should come like this..
AB
A1B1
A2B1
July 26, 2010 at 12:11 am
U can find the qry below, but this is not the optimum sulution....
select distinct a.c1, (select distinct top 1 b.c2 from asd1 b where b.c1 = a.c1) from asd1 a
July 26, 2010 at 2:32 am
I want B to also display
Which value of B? For A1 and A2 you have two values. Using GROUP BY instead of DISTINCT shows how you can explicitly choose between them:
DROP TABLE #Sample
CREATE TABLE #Sample (ColA VARCHAR(2), ColB VARCHAR(2))
INSERT INTO #Sample (ColA, ColB)
SELECT 'A', 'B' UNION ALL
SELECT 'A1', 'B1' UNION ALL
SELECT 'A2', 'B1' UNION ALL
SELECT 'A1', 'B2' UNION ALL
SELECT 'A2', 'B2'
SELECT ColA, ColB = MIN(ColB) FROM #Sample GROUP BY ColA
SELECT ColA, ColB = MAX(ColB) FROM #Sample GROUP BY ColA
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
July 26, 2010 at 3:07 am
Yes Chris, u r right.... I didn't consider groupby clause here...
July 26, 2010 at 3:15 am
Hi, U can do it by using ranking function....
select a , b from (select a, b, dense_rank() over (partition by a, order by b) as rnk from tab) T
where T.rnk = 1 or 2
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply