我有一个像这样的表
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
提前致谢
最佳答案
您没有指定您使用的 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) |
关于sql - 需要在sybase中创建pivot脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15807574/