您可以使用窗口函數的組合來得到這樣的結果:
select id,
max(case when FirstRowNumber= 1 then firstdate end) firstdate,
max(case when FirstRowNumber= 1 then itemid end) firstitemId,
max(case when LastRowNumber= 1 then lastdate end) lastdate,
max(case when LastRowNumber= 1 then itemid end) lastitemId
from
(
select id, firstdate, lastdate, itemid,
row_number() over(partition by id order by firstdate) FirstRowNumber,
row_number() over(partition by id order by lastdate desc) LastRowNumber
from yourtable
) x
where FirstRowNumber= 1
or LastRowNumber= 1
group by id
見SQL Fiddle with Demo。
此解決方案將row_number
分配給ASC/DESC日期順序中的記錄。那麼你只關心row_number = 1
的記錄。然後我應用了一個聚合和一個CASE
聲明來獲得正確的結果。
或者你可以使用一個非常難看UNPIVOT
和PIVOT
解決方案:
select *
from
(
select id,
val,
case when firstrownumber = 1 and col = 'firstdate'
then 'firstdate'
when firstrownumber = 1 and col = 'itemid'
then 'firstitemid'
when LastRowNumber = 1 and col = 'lastdate'
then 'lastdate'
when LastRowNumber = 1 and col = 'itemid'
then 'lastitemid'
else '' end col
from
(
select id,
convert(varchar(10), firstdate, 120) firstdate,
convert(varchar(10), lastdate, 120) lastdate,
cast(itemid as varchar(10)) itemid,
row_number() over(partition by id order by firstdate) FirstRowNumber,
row_number() over(partition by id order by lastdate desc) LastRowNumber
from yourtable
) x
unpivot
(
val for col in (firstdate, lastdate, itemid)
) u
) x1
pivot
(
max(val)
for col in ([firstdate], [firstitemid],
[lastdate], [lastitemid])
) p
見SQL Fiddle with Demo
*** *** SQL只是*結構化查詢語言* - 一個由許多數據庫所使用的語言系統,但不是一個數據庫產品...很多東西都是特定於供應商的 - 所以我們真的需要知道您使用的數據庫系統**(以及哪個版本)...... –
我試過了已成功獲取FirstItemId值:select ID,ItemId \t \t從(由項目Id,ID,FirstDate具有MIN(FirstDate )= FirstDate從表1中選擇項目Id,ID,ROW_NUMBER()以上(分區由ID順序由MIN(FirstDate))[ROWNUM] 基團)的 其中ROWNUM = 1 order by ID,ItemId – user1729486