网站表
WBSNumber | SiteCode | ASNumber | SITENAME
1 .......................... 11112 ........... 1 ....... ..........站点A
1 ........................ 11112 .......... 2 ............... SiteA
2 ......................... 42342 .......... 2 ......... ...... SiteB
2 ......................... 42342 .......... 1 ......... ...... SiteB
2 ......................... 42342 .......... 3 ......... ...... SiteB
3 ......................... 78965 .......... 1 ......... ...... SiteC
4 ......................... 78954 .......... 1 ......... ...... SiteD
5 ......................... 112233 .......... 1 ......... ...... SiteE
5 ......................... 112233 .......... 2 ......... ...... SiteE
我正在努力编写一些将返回所有网站列表的sql,其中包含基于最高ASNumber的唯一WBSNumber。
所以在我的情况下,我期待以下结果:
WBSNumber | SiteCode | ASNumber | SITENAME
1 ........................ 11112 .......... 2 ............... SiteA
2 ......................... 42342 .......... 3 ......... ...... SiteB
3 ......................... 78965 .......... 1 ......... ...... SiteC
4 ......................... 78954 .......... 1 ......... ...... SiteD
5 ......................... 112233 .......... 2 ......... ...... SiteE
此处WBSNumber是唯一的,仅根据最高ASNUmber选择行。
答案 0 :(得分:3)
试试这个:
SELECT WBSNumber, SiteCode, MAX(ASNumber) ASNumber, SiteName
FROM SiteTable
GROUP BY WBSNumber, SiteCode, SiteName
MAX
用于获取最高ASNumber,其他列必须包含在GROUP BY
子句中
答案 1 :(得分:1)
您可以使用分析将rownumber(从1开始增加1)分配给每个wbsnumber以获得最高ASnumber,然后选择rownumber为1 ...
with cte as
(Select s.*, Row_number() over (partition by wbsNumber order by asNumber desc) RN)
Select * from cte
where RN = 1
或在分析之前...... 我们为每个WBSNumber生成一组最大AS编号的数据,并且只允许内部联接排除所有其他记录。
SELECT s.*
FROM Site S
INNER JOIN (SELECT Max(ASNumber) mASNumber, WBSNumber From site Group by WBSNumber) S2
on S.WBSNumber = S2.WBSNumber
and S.ASNumber = S2.mASNumber
此方法可确保保留表中的所有其他数据;因此,如果您为最高ASNumber设置了不同的SiteName,我们将只获得最高AS编号的名称。
答案 2 :(得分:0)
根据您的示例数据,WBS,SiteCode和SiteName彼此都是唯一的。所以你只需要最大ASNnumber
select distinct
WBSNumber,
SiteCode,
SiteName,
Max(ASNumber) as ASNumber
from SiteTable
group by
WBSNumber,
SiteCode,
SiteName
如果情况并非如此,那么你也可以获得最大WBS ......
select distinct
Max(WBSNumber) as WBSnumber,
SiteCode,
SiteName,
Max(ASNumber) as ASNumber
from SiteTable
group by
SiteCode,
SiteName
否则我们需要更大的数据样本......或使用RowNumber()