SQL在内部联接的单行中选择COLUMNS

时间:2013-12-07 05:21:21

标签: sql select sql-server-2012

您好,我在程序中选择所需的输出时遇到问题。

以下是该方案:

我有2张桌子

_Users

_Mobiles

假设我在每个表中都有这些字段和数据:

_Users

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

_Mobiles

  **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 Mobile

1   44897065
1   44897066
1   44897067

但我想要的是将数据安排到:

UserID   Mobile1  Mobile2  Mobile3
  1     44897066 44897065 44897065

如果同一用户的另一部手机被编码,它将输出为Mobile4,依此类推..

我知道这很奇怪,但我想出于某种原因这样做:D 这是可能的,任何人都可以帮助我如何做到这一点。非常感谢大家。

2 个答案:

答案 0 :(得分:0)

试试这个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)

答案 1 :(得分:0)

这可以使用帮助,但类似这样的

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)
相关问题