从SQL Server中的连接中获取表的两行中的单行

时间:2017-08-30 13:56:44

标签: sql-server join

我需要使用Join或其他方法从表中的两行中获取一行。我有三个表Account,Account_Perm和User。帐户表有一个名为AccountNum的字段,Account_Perm有AccountNum,TeamRole和UserName的字段,User表有User name。示例数据如下。

  • 帐户==> AccountNum = 1234,5678
  • Account_Perm ==> AccountNum = 1234,TeamRole = TeamA; AccountNum = 1234,TeamRole = TeamB
  • 用户==> TeamRole = TeamA,UserName = John Smith; TeamRole = TeamB,UserName =“Casey Brown”。

我需要使用这些表,我的结果集与列(AccountNum,TeamRole,TeamRole)应如下所示。

#include <stdio.h>
#include <string.h>
#include <malloc.h>

char *str_join(char *str1, char *str2)
  {
  char *result = malloc (strlen (str1) + strlen (str2) + 1);
  strcpy (result, str1);
  strcat (result, str2);
  return result;
  }

 int main(int argc, char **argv)
   {
   char *part1 = "Hello ";
   char *part2 = "World!";
   char *joined = str_join(part1, part2);
   printf("%s\n", joined);
   free (joined);
   return 0;
   }

通过使用Join,我可以获得两行1234,John Smith和1234,Casey Brown。但是,我需要AccountNum,TeamA的用户名和TeamB的用户名。

有人可以帮忙吗?

查询:

1234, John Smith, Casey Brown

1 个答案:

答案 0 :(得分:0)

declare @Account table( AccountNum int);
insert into @Account values (1234), (5678);

declare @Account_Perm table ( AccountNum int, TeamRole varchar(100))
insert into @Account_Perm values( 1234, 'TeamA'), (1234, 'TeamB');

declare @User table (TeamRole varchar(100), UserName varchar(100));
insert into @User values ('TeamA', 'John Smith'), ('TeamB','Casey Brown');

--AccountNum, TeamRole, TeamRole) should be as below.
--1234, John Smith, Casey Brown
with cte AS
(
SELECT 
    A.AccountNum,
    AA.TeamRole,
    U.UserName
FROM 
    @Account A join @Account_Perm AA
       on A.AccountNum = AA.AccountNum
    join @User U
       on AA.TeamRole = U.TeamRole
WHERE  AA.TeamRole IN ('TeamA', 'TeamB')
)

select *
from cte pivot(max(UserName) for TeamRole in ([TeamA], [TeamB]))p