[英]SQL Select COLUMNS in a single row with inner join
嗨,我在選擇程序中所需的輸出時遇到問題。
這是場景:
我有2張桌子
_用戶
_手機
可以說我在每個表中都有這些字段和數據:
_用戶
**UserID** **Name**
1 John
2 Mark
_手機
**UserID** **Mobile**
1 44897065
1 44897066
1 44897067
2 45789071
我所知道的是我可以使用
Select a.UserID, b.Mobile
from _Users a INNER JOIN
_Mobiles b ON a.UserID = b.UserID
where UserID = 1
它將以以下格式檢索數據:
UserID手機
1 44897065
1 44897066
1 44897067
但是我想要的是將數據整理成:
UserID Mobile1 Mobile2 Mobile3
1 44897066 44897065 44897065
並且如果對同一用戶的另一個移動電話進行了編碼,它將輸出為Mobile4,依此類推。
我知道這很奇怪,但是由於某些原因我想這樣做:D這可能嗎,有人可以幫助我怎么做。 謝謝大家!謝謝。
試試這個SQL查詢..
DECLARE @cols AS NVARCHAR(MAX),@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(a.MobileCategory)
from
(
Select a.UserID as UserID, b.Mobile as Mobile,'Mobile'+ CAST(ROW_NUMBER() OVER( ORDER BY b.Mobile) AS VARCHAR) AS MobileCategory
FROM _Users a INNER JOIN
_Mobiles b ON a.UserID = b.UserID
WHERE a.UserID = 1
) a
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT UserID,' + @cols + ' from
(
Select a.UserID as UserID,b.Mobile as Mobile,''Mobile''+ CAST(ROW_NUMBER() OVER( ORDER BY b.Mobile) AS VARCHAR) AS MobileCategory
FROM _Users a INNER JOIN
_Mobiles b ON a.UserID = b.UserID
WHERE a.UserID = 1
) x
pivot
(
sum(Mobile)
for MobileCategory in (' + @cols + ')
) p '
execute(@query)
這可以使用幫助,但是像這樣
with (
select u.userid, m1.mobid, m2.mobid, .. mN.mobid
from users u
left join mobiles m1
on u.userid=m1.userid
left join mobiles m2
on u.userid=m2.userid
...
left join mobiles mN
on u.userid=mN.userid
) as mobuser
select * from mobuser
where ( m2.mobid>m1.mobid or m2.mobid is null)
and ( m3.mobid>m2.mobid or m3.mobid is null)
...
and (mN.mobid>mNMinus1.mobid or mN.mobid is null)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.