현재 목록에서 historyhour 라는 컬럼은 시간을 뜻하는데, 현재 09시 데이터가 2개가 조회됩니다.
저는 그 09시 데이터 중에 1개만 조회가 되게 하고 싶습니다..(가장 최근 데이터로)
서브쿼리 하위쿼리 등등,, 제 나름대로 써봤는데 계속 09시 데이터는 똑같이 두개가 조회되더라구요..
어떻게하면 중복이 제거된 채로 나오는지 질문드립니다. 만지기 전 쿼리로 보여드립니다..
--쿼리
SELECT O2 ,CO , LEFT(CONVERT(VARCHAR(8), CreateDate, 108),2) AS HistoryHour , CONVERT(CHAR(10),CreateDate,23) AS CreateDate FROM [dbo].[GasHistory] AS A WITH (NOLOCK) WHERE BleDeviceKey = @BleDeviceKey AND ( 1 = (CASE WHEN @Type = 'L' THEN 1 ELSE 0 END) AND (CONVERT(CHAR(10),CreateDate,23) = (SELECT TOP 1 CONVERT(CHAR(10),CreateDate,23) AS Recentdate FROM [dbo].[GasHistory] WHERE BleDeviceKey = @BleDeviceKey ORDER BY Recentdate desc ))) OR (BleDeviceKey = @BleDeviceKey AND ( 1 = (CASE WHEN @Type = 'S' THEN 1 ELSE 0 END) AND (CONVERT(CHAR(10),CreateDate,23) = @SelectDate))) ORDER BY HistoryHour ASC;
--조회 결과
o2 co historyHour createDate
18 1.5 01 2017-09-25
17 3.0 07 2017-09-25
20.9 1.0 09 2017-09-25
15 3.5 09 2017-09-25
with t (o2, co, historyHour, createDate) as ( select 18 , 1.5 , 01 , convert(DATETIME,'2017-09-25 10:11:11',120) union all select 17 , 3.0 , 07 , convert(DATETIME,'2017-09-25 10:11:12',120) union all select 20.9 , 1.0 , 09 , convert(DATETIME,'2017-09-25 10:11:13',120) union all select 15 , 3.5 , 09 , convert(DATETIME, '2017-09-25 10:11:14 ',120) ) select a.* from ( select t.* , ROW_NUMBER() OVER(PARTITION BY CONVERT(VARCHAR,createDate,112) ORDER BY createDate DESC) rn from t ) a where rn = 1
SELECT * FROM (SELECT a.o2 , a.co , CONVERT(CHAR(2), a.CreateDate, 24) AS HistoryHour , CONVERT(CHAR , a.CreateDate, 23) AS CreateDate , ROW_NUMBER() OVER( PARTITION BY CONVERT(CHAR(2), a.CreateDate, 24) -- 시간대별 ORDER BY a.CreateDate DESC -- 최종시간 ) rn FROM [dbo].[GasHistory] a WITH (NOLOCK) INNER JOIN (-- 조회 타입에 따라 조회일자 가져오기 -- SELECT CAST( CASE @Type WHEN 'L' THEN CONVERT(CHAR, MAX(CreateDate), 23) WHEN 'S' THEN @SelectDate END AS datetime) AS sdt FROM [dbo].[GasHistory] WITH (NOLOCK) WHERE BleDeviceKey = @BleDeviceKey ) b ON a.CreateDate >= b.sdt AND a.CreateDate < DATEADD(day, 1, b.sdt) WHERE a.BleDeviceKey = @BleDeviceKey ) a WHERE rn = 1 ;