简体   繁体   中英

SQL Select COLUMNS in a single row with inner join

Hi I am having problem with selecting my desired output in my program.

Here's the scenario:

I have 2 tables

_Users

_Mobiles

Lets say I have these fields and data in each tables:

_Users

  **UserID**        **Name** 
      1               John
      2               Mark

_Mobiles

  **UserID**        **Mobile** 
      1              44897065
      1              44897066
      1              44897067
      2              45789071

What I know is that I can use

Select a.UserID, b.Mobile
from _Users a INNER JOIN
_Mobiles b ON a.UserID = b.UserID
where UserID = 1

which will retrieve data in this format:

UserID Mobile

1   44897065
1   44897066
1   44897067

but what I want is to arrange the data into:

UserID   Mobile1  Mobile2  Mobile3
  1     44897066 44897065 44897065

and if another mobile for the same user is encoded, it will output as Mobile4 and so on..

I know this is strange but I want to do it for some reason :D Is this possible and can anybody help me how to do it. Thank you so much everyone.

try this Sql query..

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)

This could use help, but something like this

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM