Quantcast select specific group trong sql

select specific group trong sql

by Neon Quach 7. October 2010 16:39

Hãy tưởng tượng bạn chạy câu lệnh:

SELECT description, location_id FROM teams

Danh sách các kết quả trả về:
----------------------------------
Bayer Leverkusen    1
Hamburger SV    1
Werder Bremen    1
Schalke 04    1
Bayern München    1
Hoffenheim    1
.........
Chelsea    2
Manchester United    2
Arsenal    2
Tottenham Hotspur    2
Liverpool    2
Manchester City    2
.........

Mình chỉ list kq trả về dạng rút gọn, còn rất nhiều giá trị location_id khác nhau (tới 145 location lận). Giờ bạn có thêm 1 yêu cầu là chỉ select các teams ở group 1 và group 134 chẳng hạn, do table bảng teams có location_id giống như group nên có thể các bạn hơi confused.

Câu trả lời là DENSE_RANK. DENSE_RANK là hàm trả về số group được xác định bởi mệnh đề Order By.

select id, Description, location_id, DENSE_RANK() OVER(order by location_id) as NoGroup from teams

KQ:

id   Description   location_id   NoGroup
------------------------------------------
1    Bayer Leverkusen    1    1
2    Hamburger SV    1    1
3    Werder Bremen    1    1
4    Schalke 04    1    1
5    Bayern München    1    1
................
4233    Underhill    142    133
4234    Black Rhinos    142    133
4243    South Africa    145    134
4246    Mexico    145    134
4248    Uruguay    145    134
4249    France    145    134

OK, việc còn lại là select group với nhóm 1 và nhóm 134

select Description, location_id FROM

(select id, Description, location_id, DENSE_RANK() OVER(order by location_id) as NoGroup from teams) as T

where NoGroup in (1,134)


Nhấn F5 và xem kết quả nhé, hope this help

Tags: ,


Categories: sql

blog comments powered by Disqus

About me

I'm  currently employed as Software developer at devinition.com and also a Microsoft Certified Technology Specialist (MCTS), Microsoft Certified Professional Developer (MCPD) in Net Framework 2.0 and 3.5: Web Applications and MCTS .NET Framework 3.5, ADO.NET Applications

Powered by BlogEngine.NET 2.5.0.5 - Eco Theme by n3o Web Designers