【问题标题】:SQL Select COLUMNS in a single row with inner joinSQL 在具有内部联接的单行中选择列
【发布时间】:2013-12-07 05:21:20
【问题描述】:

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

这是场景:

我有两张桌子

_用户

_手机

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

_用户

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

它将以这种格式检索数据:

用户 ID 移动

1   44897065
1   44897066
1   44897067

但我想要的是将数据排列成:

UserID   Mobile1  Mobile2  Mobile3
  1     44897066 44897065 44897065

如果同一用户的另一个手机被编码,它将输出为 Mobile4 等等..

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

【问题讨论】:

  • 如果您在sql server 中,您可以对其进行透视。您能指定您使用的是哪个数据库吗?
  • 如果你使用MySql,你看看GROUP_CONCAT,它不是你需要的,但它可能对你有帮助
  • 嗨@snyder,我使用的是SQL Server 2012。谢谢你,我会研究pivot,但如果可以的话,非常感谢简单的例子,谢谢。

标签: sql select sql-server-2012


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这可能需要帮助,但是像这样

    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)
    

    【讨论】:

      猜你喜欢
      • 2023-02-16
      • 1970-01-01
      • 2017-01-01
      • 2010-12-26
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      相关资源
      最近更新 更多