当前位置: 代码迷 >> Sql Server >> 新人 求大神帮忙,该怎么处理
  详细解决方案

新人 求大神帮忙,该怎么处理

热度:418   发布时间:2016-04-24 10:29:49.0
新人 求大神帮忙
手上有两张表 A 和B 表

A表的数据如下
A1 A2 A3
1    1    3
1    2    4 
2    2    3

B表的数据如下
B1 B2    B3
1    1     1,2,3 
1     2     2
2      2    1

其中 A表中的A1 A2 和 B 表中的 B1 B2 是相互联系的

想得到C表中的如下数据
C1 C2 C3 C4
1    1    3     1,2,3
1   2    4        2
2   2    2        1

------解决方案--------------------
这样?
----------------------------------------------------------------
-- Author  :DBA_HuangZJ(发粪涂墙)
-- Date    :2014-05-22 11:27:51
-- Version:
--      Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64) 
-- Apr  2 2010 15:48:46 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据[A]
if object_id('[A]') is not null drop table [A]
go 
create table [A]([cid] int,[gid] int,[aid] nvarchar(10))
insert [A]
select 1001,2,'1,2,3' union all
select 1001,1,'1,3' union all
select 1002,1,'1,2'
--> 测试数据[b]
if object_id('[b]') is not null drop table [b]
go 
create table [b]([cid] int,[gid] int,[uid] int,[bid] int)
insert [b]
select 1001,1,1,1 union all
select 1002,2,1,2
--------------生成数据--------------------------

select B.CID,B.GID,B.UID,B.BID,A.AID
from [b] LEFT JOIN [A] ON B.CID=A.CID AND B.GID=A.GID

----------------结果----------------------------
/* 
CID         GID         UID         BID         AID
----------- ----------- ----------- ----------- ----------
1001        1           1           1           1,3
1002        2           1           2           NULL
*/
  相关解决方案