在保留信息的同时将表合并到新表中

时间:2013-10-07 09:15:29

标签: sql sql-server

我提前道歉,因为标题不是很具描述性。

我有大约40多个表,每个表具有相同的表格布局列,并且数据保存为一列。我想在所有表中使用不同的列,并将它们合并到一个表中。混乱?让我说明..

SRCTbl01:

ID  TYPE  COLR1  INSTOCK
-----------------------
1    B     RED    YES
2    B     BLUE   YES
3    P     GREEN  NO
4    B     BLACK  YES

SRCTbl02:

ID  TYPE  COLR1  INSTOCK
-----------------------
1    B     RED    YES
2    B     BLUE   NO
3    P     GREEN  YES
4    B     BLACK  YES

SRCTbl03:

ID  TYPE  COLR1  INSTOCK
-----------------------
1    B     RED    YES
2    B     BLUE   NO
3    P     GREEN  NO
4    B     BLACK  NO

结果:(要排除P类型)

ID  TYPE  COLR1  SRCTbl01  SRCTbl02  SRCTbl03
----------------------------------------------
1    B     RED    YES       YES       YES
2    B     BLUE   YES       NO        NO
4    B     BLACK  YES       YES       NO

最后,我想让桌子看起来像这样:

INSTOCK表:

Customer  RED  BLUE  BLACK
---------------------------
SRCTbl1   YES  YES   YES
SRCTbl2   YES  NO    YES
SRCTbl3   YES  NO    NO

我不能完全确定我是否可以直接操作表格看起来像最后一次迭代所以我想我应该问如何将它放到第一个结果对我来说似乎更简单。

感谢您的帮助,我花了整整8个小时就已经找到了实现它的方法,所以我来这里问专家。

编辑:为了澄清,我在实现上面说明的结果方面没有成功。我尝试过使用SELECT .. Union SELECT和FULL JOINS。

使用此代码导致重复(我试图获得INSTOCK)

SELECT 01.INSTOCK, 02.INSTOCK, 03.INSTOCK
FROM dbo.SRCTbl01 AS 01, dbo.SRCTbl02 AS 02, dbo.SRCTbl03 AS 03
WHERE 01.TYPE='B'

我尝试了很多,但这可能是我最接近的。

2 个答案:

答案 0 :(得分:1)

你可以做一些这样的事情,一个一个:

首先使用union进行压平,然后按客户的每种颜色选择max'instock'(MAX将作为'YES'>'NO'工作)

select Customer, MAX(RED) as RED, MAX(BLUE) as BLUE, MAX(BLACK) as BLACK
FROM(
  SELECT 'SRCTbl01' as Customer, 
       CASE WHEN COLR1 = 'RED' then INSTOCK ELSE 'NO' END as RED,
       CASE WHEN COLR1 = 'BLUE' then INSTOCK ELSE 'NO' END as BLUE,
       CASE WHEN COLR1 = 'BLACK' then INSTOCK ELSE 'NO' END as BLACK
  FROM SRCTbl01
  WHERE  Type <> 'P'
UNION
  SELECT 'SRCTbl02' as Customer, 
       CASE WHEN COLR1 = 'RED' then INSTOCK ELSE 'NO' END as RED,
       CASE WHEN COLR1 = 'BLUE' then INSTOCK ELSE 'NO' END as BLUE,
       CASE WHEN COLR1 = 'BLACK' then INSTOCK ELSE 'NO' END as BLACK
  FROM SRCTbl02
  WHERE  Type <> 'P'
UNION
  SELECT 'SRCTbl03' as Customer, 
       CASE WHEN COLR1 = 'RED' then INSTOCK ELSE 'NO' END as RED,
       CASE WHEN COLR1 = 'BLUE' then INSTOCK ELSE 'NO' END as BLUE,
       CASE WHEN COLR1 = 'BLACK' then INSTOCK ELSE 'NO' END as BLACK
  FROM SRCTbl03
  WHERE  Type <> 'P'
) as a
GROUP BY Customer

(您只需要添加CREATE TABLE INSTOCK as <codegiven>

请参阅SqlFiddle

答案 1 :(得分:0)

使用UNION和PIVOT,这样的东西应该做你想要的(PIVOT应该适用于SQL Server 2005及更新版本):

SELECT Customer, [Red], [Blue], [Black]
FROM (
    SELECT 'SRCTbl01' AS Customer, COLR1, INSTOCK FROM SRCTbl01 WHERE Type <> 'P'
    UNION
    SELECT 'SRCTbl02' AS Customer, COLR1, INSTOCK FROM SRCTbl02 WHERE Type <> 'P'
    UNION
    SELECT 'SRCTbl03' AS Customer, COLR1, INSTOCK FROM SRCTbl03 WHERE Type <> 'P'
    /* UNION ... */
) AS SRC
PIVOT (
    MAX(INSTOCK)
    FOR COLR1 IN ([Red], [Blue], [Black])
) AS pvt