Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Get only a row data 4 each ID if other than Defaul

Author  Topic 

micnie_2020
Posting Yak Master

232 Posts

Posted - 2014-11-30 : 21:13:35
Hi All,

I have set data as

ID NAME GROUP
1 MIC DEFAULT
1 MIC TERR
2 JAMES DEFAULT
3 KIM HOL

Output must be:-

ID NAME GROUP
1 MIC TERR << IF there is other than Default value, drop default value >>
2 JAMES DEFAULT
3 KIM HOL


Please advise.

Thank you.

Regards,
Micheale

MuralikrishnaVeera
Posting Yak Master

129 Posts

Posted - 2014-12-01 : 03:46:36
May be this...

METHOD 1 :



CREATE TABLE #temp(ID int,NAME VARCHAR(100),[GROUP] VARCHAR(100))

INSERT INTO #temp(ID,NAME,[GROUP]) VALUES(1,'MIC','DEFAULT'),(1,'MIC','TERR'),(2,'JAMES','DEFAULT'),(3,'KIM','HOL')

SELECT a.ID
,a.NAme
,a.[Group]
FROM
(
SELECT *
,CASE WHEN COUNT(ID)OVER (PARTITIOn BY ID)>1 THEN (SELECT t2.[GROUP] FROM dbo.#temp t2 WHERE t.ID = t2.ID AND t2.[GROUP] !='Default')
ELSE t.[GROUP] END AS 'GroupCheck'
FROM dbo.#temp t
) a
WHERE a.[Group] =a.GroupCheck

DROP TABLE dbo.#temp



METHOD 2:


SELECT a.*
FROM
(
SELECT * FROM #temp
) a
LEFT JOIN
(
SELECT * FROM #temp t WHERE (t.[GROUP] != 'Default' AND ID IN (SELECT #temp.ID FROM #temp))
) b
ON a.ID = b.ID
WHERE a.[GROUP] = b.[GROUP] OR b.[GROUP] IS NULL

---------------
Murali Krishna

You live only once ..If you do it right once is enough.......
Go to Top of Page

cvipin
Yak Posting Veteran

51 Posts

Posted - 2014-12-02 : 20:18:09
SELECT *
FROM
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY CASE WHEN [GROUP] = 'DEFAULT' THEN 2 ELSE 1 END) RowNum
FROM YourTable t
) T
WHERE RowNum = 1
Go to Top of Page
   

- Advertisement -