0

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

我有大约 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

最后,我想让表格看起来像这样:

进货表:

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'

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

4

2 回答 2

1

你可以做这样的事情,一气呵成:

您首先用联合压平,然后按客户为每种颜色获取最大“库存”(MAX 将作为“是”>“否”工作)

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

于 2013-10-07T09:32:02.237 回答
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
于 2013-10-07T09:48:59.330 回答