再向c添加两列(Table1)。主键是IMSI。如果IMSI有2个或更多APN,请将其填充到其他列(apn2,apn3)。
查询结果1:
T
预期输出:
+------+--------+------------------+-----+
| IMSI | MSISDN | ROUTING_CATEGORY | apn |
+------+--------+------------------+-----+
| AAAA | BBBBB | CCCCCC | NET |
| AAAA | BBBBB | CCCCCC | MMS |
| AAAA | BBBBB | CCCCCC | SSS |
| LLLL | PPPPP | FFFFFF | NET |
+------+--------+------------------+-----+
我的查询:
╔══════╦════════╦══════════════════╦═════╦══════╦══════╗
║ IMSI ║ MSISDN ║ ROUTING_CATEGORY ║ apn ║ apn2 ║ apn3 ║
╠══════╬════════╬══════════════════╬═════╬══════╬══════╣
║ AAAA ║ BBBBB ║ CCCCCC ║ NET ║ MMS ║ SSS ║
║ LLLL ║ PPPPP ║ FFFFFF ║ NET ║ ║ ║
╚══════╩════════╩══════════════════╩═════╩══════╩══════╝
答案 0 :(得分:1)
You can do something like this:
Select IMSI, MSISDN, ROUTING_CATEGORY,
[1] as apn1, [2] as apn2, [3] as apn3
from
(Select IMSI, MSISDN, ROUTING_CATEGORY, apn,
ROW_NUMBER() over(partition by imsi order by apn) as r
from @t
)as c
PIVOT
(
max(apn)
for r in ([1], [2], [3])
)AS p
答案 1 :(得分:0)
What is the purpose of this query? reporting?
one option is to create a temporary table to insert the distinct values by excluding the apn field then use a loop (while/cursor) to alter the temp table to add the columns dynamically and update the same based on the number of apn field for each unique key.
With Pivot you need to manually specify the columns or else you may need to use dynamic sql with pivot to generate the column.