将具有多个返回数据的行移至列以确保SQL Server结果中的一行

时间:2018-08-09 13:33:31

标签: sql sql-server

我目前有一个可以导致多行的联接。与其使用联接来获取返回结果,我不希望只返回一个联接表中的特定列,而是将联接表中的特定列列在列中,以仅显示每一行。

select u.city, u.state, u.county, u.zip, c.local_code
from usa u
left join code c where c.zip = u.zip 
where zip = '90210'

抽样结果

city       state   county         zip     local_code
----------------------------------------------------
salt lake  utah    lake county    90210   12A
salt pond  utah    lake county    90210   12C
sea salt   utah    lake county    90210   12B

由于一个邮递区号有多个城市,我想将其分成几个单独的列,并将其命名为local_code_1-local_code_6以填充一行中通过的所有潜在代码,并删除城市名称。

所以我想要这样的结果:

state   county         zip     local_code_1 local_code_2 local_code_3 local_code_4 local_code_5 local_code_6
utah    lake county    90210   12A          12C          12B

3 个答案:

答案 0 :(得分:0)

此代码需要一些工作才能完成您的首选项,但是我认为这样的事情可能会对您有所帮助。这是多个CTE的组合,每个CTE都由另一个行号连接。

;WITH CTE AS 
(
    SELECT U.CITY, U.STATE, U.COUNTY, U.ZIP, C.LOCAL_CODE
    FROM USA AS U
    LEFT JOIN CODE C WHERE C.ZIP = U.ZIP 
    WHERE ZIP= '90210'
)

SELECT *
FROM CTE AS C
LEFT JOIN CTE_JoinedTable AS C2 ON C.ID = C2.ID AND C2.RowNumb = 2
LEFT JOIN CTE_JoinedTable AS C3 ON C.ID = C3.ID AND C3.RowNumb = 3
LEFT JOIN CTE_JoinedTable AS C4 ON C.ID = C4.ID AND C3.RowNumb = 4
LEFT JOIN CTE_JoinedTable AS C5 ON C.ID = C5.ID AND C3.RowNumb = 5
LEFT JOIN CTE_JoinedTable AS C6 ON C.ID = C6.ID AND C3.RowNumb = 6
WHERE C.RowNumb = 1

答案 1 :(得分:0)

正如上面Andrea所暗示的,您正在搜索Pivot构造。您可以按州,县和邮政编码指定序列nr,然后按此值指定数据透视。

DECLARE @t TABLE([city] VARCHAR(255),[state] VARCHAR(255),[county] VARCHAR(255),[zip] VARCHAR(25),[local_code] VARCHAR(25));
INSERT INTO @t VALUES
 ('salt lake','utah','lake county','90210','12A')
,('salt pond','utah','lake county','90210','12C')
,('sea salt','utah','lake county','90210','12B');

SELECT pvt.*
FROM (
     SELECT [state]
           ,[county]
           ,[zip]
           ,[local_code]
           ,[seq]=ROW_NUMBER() OVER(PARTITION BY [state],[county],[zip] ORDER BY [local_code] ASC)
     FROM @t
) src PIVOT(MAX(local_code) FOR seq IN([1],[2],[3],[4],[5],[6])) AS pvt;

屈服

state           county          zip        1     2     3     4     5     6
--------------- --------------- ---------- ----- ----- ----- ----- ----- -----
utah            lake county     90210      12A   12B   12C   NULL  NULL  NULL

答案 2 :(得分:-1)

您可以使用数据透视

select state,country,zip,[1] as local_code1,
[2] as local_code2,
[3] as local_code3,
[4] as local_code4,
[5] as local_code5,
[6] as local_code6
from 
(
   select state,country,zip,local_code,
    rn= row_number() over (partition by state,country,zip order by local_code)
    from t
  ) sr PIVOT (max(local_code) for rn in ([1],[2],[3],[4],[5],[6]) ) as pvt

http://sqlfiddle.com/#!18/358ae/40

 state  country     zip     local_code1     local_code2     local_code3     local_code4     local_code5     local_code6
utah   lake county 90210       12A            12B              12C            (null)        (null)        (null)