查询将值从列移动到行

时间:2015-12-25 12:19:58

标签: sql sql-server

我有两个表,我想合并第三个表中的数据,如下所示,

表1:

<div id='test' onclick='alert("ok");'>Check</div>

表2

User Id  Account1  Account 2  
-------  --------  ---------
Lucky    Twitter   Facebook  
Happy    Orkut     GooglePlus

我希望结果为:

User Id  AccountStatus 
-------  ------------- 
Lucky    Active  

关于如何做的任何想法?

3 个答案:

答案 0 :(得分:2)

只需unpivot数据即可获得格式化结果

使用CROSS APPLY运算符

SELECT [user id], 
       account 
FROM   table1 A 
       CROSS apply (VALUES (account1), 
                           (account2)) cs(account) 
WHERE  EXISTS (SELECT 1 
               FROM   table2 B 
               WHERE  A.[user id] = B.[user id]
                 AND  B.AccountStatus = 'Active') 

或使用UNION ALLunpivot数据

SELECT * 
FROM   (SELECT [user id], 
               account1  as account
        FROM   table1 
        UNION ALL 
        SELECT [user id], 
               account2 
        FROM   table1) A 
WHERE  EXISTS (SELECT 1 
               FROM   table2 B 
               WHERE  A.[user id] = B.[user id]
                 AND  B.AccountStatus = 'Active') 

答案 1 :(得分:1)

SQL Server本身支持UNPIVOT,因此您应该使用它:

SELECT UserI
FROM
(
    SELECT A.UserId, Account1, Account2
    FROM Account A
        JOIN AccountStatus S ON S.UserId = A.UserId
    WHERE S.AccountStatus = 'Active'
) AS acc
UNPIVOT 
(
   Account FOR Acc IN (Account1, Account2)
) AS up;

我不知道它是否更快,但只需在两个地方(SELECTUNPIVOT内)添加列,即可轻松扩展您的帐户类型。

答案 2 :(得分:1)

; With cteActiveAccount As(
   Select UserId
   From Table2 where AccountStatus = 'Active'
 )
, cteAccountFilterdOnes As(
  Select r.UserId
         r.Account1 as Account 
  from Table1 r
  inner join cteActiveAccount c on
      r.UserId = c.UserId
  union all
  Select r.UserId
         r.Account2 as Account 
  from Table1 r
  inner join cteActiveAccount c on
      r.UserId = c.UserId
  )

从cteAccountFilterdOnes

中选择*