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
 General SQL Server Forums
 New to SQL Server Programming
 condition max

Author  Topic 

waterduck
Aged Yak Warrior

982 Posts

Posted - 2013-12-20 : 02:45:24
[code]declare @a table(col1 varchar(10), col2 varchar)
insert into @a select
'a', 1 union all select
'a', 5 union all select
'a', 7 union all select
'b', 1 union all select
'b', 3 union all select
'c', 1

/*
require output
a, 5
b, 3
c, 1
*/[/code]

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2013-12-20 : 03:01:47
what's the logic ?


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2013-12-20 : 11:53:27
I don't know the logic either, but I took a shot in the dark:
declare @a table(col1 varchar(10), col2 varchar)
insert into @a select
'a', 1 union all select
'a', 5 union all select
'a', 7 union all select
'b', 1 union all select
'b', 3 union all select
'c', 1


;WITH Cte AS
(
SELECT col1, col2, ROW_NUMBER() OVER (PARTITION BY col1 ORDER BY col2 ASC) AS RowNum
FROM @a
)


SELECT
A.Col1,
COALESCE(B.Col2, A.Col2) AS col2
FROM
Cte AS A
LEFT OUTER JOIN
Cte AS B
ON A.col1 = B.col1
AND A.RowNum + 1 = B.RowNum
WHERE
A.RowNum = 1
OR B.RowNum = 2

If that doesn't work, please explain the logic for how to select the values.
Go to Top of Page

waterduck
Aged Yak Warrior

982 Posts

Posted - 2013-12-20 : 12:20:36
sorry nt enuf time to post everything at the moment...tats why it look ugly

if count col2 > 1 then get second value
if count col2 = 1 then get the only value

without table spool.....good for 20m records.

query 1
-------
SELECT *
FROM @a a
OUTER APPLY(
SELECT TOP 1 *
FROM (SELECT TOP 2 *
FROM @a b
WHERE a.col1 = b.col1
ORDER BY col2)tmp
ORDER BY col2 DESC)tmp



query 2
-------
SELECT *
FROM @a a
OUTER APPLY(
SELECT *
, rn = ROW_NUMBER() OVER (PARTITION BY col1 ORDER BY col2)
, cnt = COUNT(1) OVER (PARTITION BY col1)
FROM @a b
WHERE a.col1 = b.col1
)tmp
WHERE (cnt = 3 AND rn = cnt - 1)
OR (cnt = 2 AND rn = cnt)
OR (cnt = 1 AND rn = 1)


Edit formating
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-12-21 : 01:00:41
[code]
SELECT col1,col2
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY col1 ORDER BY col1) AS Rn,
COUNT(1) OVER (PARTITION BY col1) AS Cnt,*
FROM Table
)t
WHERE Rn = 1
OR (Rn=2 AND Cnt > 1)
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -