繁体   English   中英

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

[英]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.

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