USE TEMPDB GO IF EXISTS (SELECT * FROM SYS.TABLES WHERE NAME = 'T' AND type = 'U') DROP TABLE T GO CREATE TABLE T ( id int primary key, V1 int, V2 int ) INSERT INTO T SELECT 1, 50, 20 UNION ALL SELECT 2, 60, 30 UNION ALL SELECT 3, 70, 40 UNION ALL SELECT 4, 45, 25 UNION ALL SELECT 5, 55, 35 UNION ALL SELECT 6, 65, 15 UNION ALL SELECT 7, 75, 35 UNION ALL SELECT 8, 90, 60 UNION ALL SELECT 9, 45, 32 GO SELECT * FROM T /* id V1 V2 ----------- 1 50 20 2 60 30 3 70 40 4 45 25 5 55 35 6 65 15 7 75 35 8 90 60 9 45 32 */ |
-------------------------------------------------------------------------------------------- --Louis -------------------------------------------------------------------------------------------- SELECT T.id, (SELECT MAX(v1) FROM T AS t2 WHERE T.id BETWEEN t2.id -2 AND t2.id + 2 HAVING COUNT(*) = 5) , (SELECT MIN(v2) FROM T AS t2 WHERE T.id BETWEEN t2.id -2 AND t2.id + 2 HAVING COUNT(*) = 5) FROM T GROUP BY T.id GO |
-------------------------------------------------------------------------------------------- --Steve Join -------------------------------------------------------------------------------------------- SELECT T1.id, CASE WHEN COUNT(*) = 5 THEN MAX(T2.V1) END AS V1, CASE WHEN COUNT(*) = 5 THEN MIN(T2.V2) END AS V2 FROM T AS T1 JOIN T AS T2 ON T2.id BETWEEN T1.id - 2 AND T1.id + 2 GROUP BY T1.id GO |
-------------------------------------------------------------------------------------------- --Steve Cross Join -------------------------------------------------------------------------------------------- SELECT MIN(CASE WHEN Five.N = 0 THEN id END) AS id, CASE WHEN COUNT(*) = 5 THEN MAX(V1) END AS V1, CASE WHEN COUNT(*) = 5 THEN MIN(V2) END AS V2 FROM T CROSS JOIN ( SELECT -2 AS N UNION ALL SELECT -1 UNION ALL SELECT 1 ) AS Five GROUP BY id+N HAVING COUNT(CASE WHEN Five.N = 0 THEN 1 END) > 0 GO |
-->
select a.id,b.v1,b.v2
from t a
cross apply
(
select case when count(*) = 5 then max(V1 ) end as v1
,case when count(*) = 5 then min( V2) end as v2
from t
where id between a.id - 2 and a.id + 2
) b
'연구개발 > DBA' 카테고리의 다른 글
SQL Server에서 글로벌 변수 구현하기 (0) | 2009.07.29 |
---|---|
파생된 테이블 사용 시 발생하는 구문 오류 (0) | 2009.07.29 |
같은 그룹의 데이터를 붙여서 출력하기 (0) | 2009.07.29 |
Update Statistics undocumented 옵션 (0) | 2009.07.29 |
쿼리 힌트 - OPTION 절 (0) | 2009.07.29 |