[英]SQL Server Query group by analytic
我有這樣的桌子
Id scid name namesuffix nameId namesuffixid fullname
--------------------------------------------------------
1 1 a a 100 100 a
2 1 a b 100 101 ab
3 1 b c 101 102 abc
4 1 c d 102 103 abcd
5 2 e e 104 104 e
6 2 e f 104 105 ef
7 2 f g 105 106 efg
8 3 i i 107 107 i
9 3 i j 107 108 ij
10 3 j k 108 109 ijk
11 3 k l 109 110 ijkl
12 3 l m 110 111 ijklm
for each scid (group by scid)
select firstRow fullName
Last row fullName
預期產量
id scid fullname
-------------------
1 1 a
4 1 abcd
5 2 e
7 2 efg
8 3 i
12 3 ijklm
我嘗試了first_value
和last_value
分析函數,但是這些行在重復,沒有得到預期的結果。
任何幫助表示贊賞。
您可以按照建議使用FIRST_VALUE
和LAST_VALUE
:
SELECT scid,
FIRST_VALUE(id) OVER(PARTITION BY scid ORDER BY id
ROWS UNBOUNDED PRECEDING) AS id,
FIRST_VALUE(fullname) OVER(PARTITION BY scid ORDER BY id
ROWS UNBOUNDED PRECEDING) AS fullname
FROM tab_name
UNION
SELECT scid,
LAST_VALUE(id) OVER(PARTITION BY scid ORDER BY id
RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS id,
LAST_VALUE(fullname) OVER(PARTITION BY scid ORDER BY id
RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS fullname
FROM tab_name
ORDER BY scid, id;
另一種選擇是使用ROW_NUMBER()
和COUNT
select
id, scid, fullname
from (
select
*, row_number() over (partition by scid order by id) rn
, count(*) over (partition by scid) cnt
from
myTable
) t
where
rn = 1
or rn = cnt
還有其他沒有窗口功能的方法:
select t.*
from t join
(select min(id) as min_id, max(id) as max_id
from t
group by sc_id
) tt
on t.id in (min_id, max_id);
我只建議這樣做,因為有很多方法可以做您想要的。 如果性能是一個問題,則您可能需要嘗試不同的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.