我有一张像
这样的表格ID ENVI SERVER GROUP ACTIVE
== ==== ====== ====== ======
1 Developent AREGION_1 A 1
2 Developent AREGION_2 A 1
3 Developent AREGION_3 A 1
4 Developent BREGION_1 B 1
5 Developent BREGION_2 B 1
6 Developent BREGION_3 B 1
7 Developent CREGION_1 C 1
8 Developent CREGION_3 C 1
9 Developent A1REGION A 1
10 Developent A2REGION A 1
11 Developent ABCREGION A 1
我需要编写一个带有输入参数ENVI
的sp,它将返回如下所示的结果
ENVI A B C
==== ========= ========= =========
Development AREGION_1 BREGION_1 CREGION_1 (All servers Ending with _1)
Development AREGION_2 BREGION_2 (All servers Ending with _2)
Development AREGION_3 BREGION_3 CREGION_3 (All servers Ending with _3)
Development A1REGION
Development A2REGION
Development ABCREGION
条件是
所有以_
编号结尾的服务器都应按第一个排序顺序排列。
如果任何一列没有该行的值,则该字段应该为null或为空。
任何组下随机名称的任何服务器都必须放在该组的最后一个位置。
请帮我创建sp
提前致谢
答案 0 :(得分:2)
您没有指定正在使用的sybase版本,此答案假设您拥有可以访问窗口函数的版本。 Sybase没有PIVOT函数,因此您必须使用带有CASE
表达式的聚合函数来复制它。
以下代码应该得到您想要的结果:
select envi,
max(case when serverGroup = 'A' then server end) as A,
max(case when serverGroup = 'B' then server end) as B,
max(case when serverGroup = 'C' then server end) as C
from
(
select envi,
server,
serverGroup,
case
when frn > rn then frn
else rn
end rn
from
(
select envi,
server,
serverGroup,
case
when charindex('_', SERVER) = 0
then 0
else substring(SERVER, charindex('_', SERVER)+1, len(SERVER))
end frn,
row_number() over(partition by envi, serverGroup
order by substring(SERVER, charindex('_', SERVER), len(SERVER)+1)) rn
from ytable
) d
) x
group by envi, rn
order by rn;
见SQL Fiddle with Demo。注意:该演示在SQL Server上。
这给出了结果:
| ENVI | A | B | C |
--------------------------------------------------
| Developent | AREGION_1 | BREGION_1 | CREGION_1 |
| Developent | AREGION_2 | BREGION_2 | (null) |
| Developent | AREGION_3 | BREGION_3 | CREGION_3 |
| Developent | A1REGION | (null) | (null) |
| Developent | A2REGION | (null) | (null) |
| Developent | ABCREGION | (null) | (null) |
答案 1 :(得分:0)
这是一个聚合查询,但您的最终结果不包含其中一个聚合列(修改后的服务器名称)。
select envi,
max(case when group = 'A' then server end) as A,
max(case when group = 'B' then server end) as B,
max(case when group = 'C' then server end) as C
from t
group by envi,
(case when server like '%[_]%' and server not like '%[_]%[^0-9]%'
then left(server, charindex('_', server) - 1)
else server
end)
like
逻辑查找具有下划线且仅在下划线后面有数字的服务器名称。