SQL行的组合

时间:2015-08-29 11:21:02

标签: sql sql-server

我有一个包含以下结构的表,我希望使用表结构table2将数据填充到此表的另一个表中

Table1

╔═══════╦═══════╗
║ State ║ City  ║
╠═══════╬═══════╣
║ A     ║ AA    ║
║ B     ║ BB    ║
║ C     ║ CC    ║
║ D     ║ DD    ║
╚═══════╩═══════╝

Table2 

╔═══════════╦═════════╦═══════════╦═══════════╗
║ SrcState1 ║ SrcCity ║ DestState ║ DestCity  ║
╠═══════════╬═════════╬═══════════╬═══════════╣
║ A         ║ AA      ║ B         ║ BB        ║
║ A         ║ AA      ║ C         ║ CC        ║
║ A         ║ AA      ║ D         ║ DD        ║
║           ║         ║           ║           ║
║ B         ║ BB      ║ A         ║ AA        ║
║ B         ║ BB      ║ C         ║ CC        ║
║ B         ║ BB      ║ D         ║ DD        ║
║           ║         ║           ║           ║
║ C         ║ CC      ║ A         ║ AA        ║
║ C         ║ CC      ║ B         ║ BB        ║
║ C         ║ CC      ║ D         ║ DD        ║
║ D         ║ DD      ║ A         ║ AA        ║
║ D         ║ DD      ║ B         ║ BB        ║
║ D         ║ DD      ║ C         ║ CC        ║
╚═══════════╩═════════╩═══════════╩═══════════╝   

修改 实际上它应该是这样的:

    ╔═══════════╦═════════╦═══════════╦═══════════╗
    ║ SrcState1 ║ SrcCity ║ DestState ║ DestCity  ║
    ╠═══════════╬═════════╬═══════════╬═══════════╣
    ║ A         ║ AA      ║ B         ║ BB        ║
    ║ A         ║ AA      ║ C         ║ CC        ║
    ║ A         ║ AA      ║ D         ║ DD        ║
    ║           ║         ║           ║           ║
    ║ B         ║ BB      ║ C         ║ CC        ║
    ║ B         ║ BB      ║ D         ║ DD        ║
    ║           ║         ║           ║           ║
    ║ C         ║ CC      ║ D         ║ DD        ║
    ╚═══════════╩═════════╩═══════════╩═══════════╝   

2 个答案:

答案 0 :(得分:1)

您可以使用CROSS JOIN生成笛卡儿积<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <a href="#" class="btn btn-primary sendOrderToSage" data-id="97" disabled="disabled">This will always return false.</a><br/>并在tab x tab中排除:

此解决方案适用于原始问题。

<强> SqlFiddleDemo

WHERE tab.state <> tab.state

对于未来陈述您的问题,如果您想获得以下内容,请使用shA.t Solution

CREATE TABLE tab(state NVARCHAR(10), City NVARCHAR(10));

INSERT INTO tab(state, city)
VALUES ('A', 'AA'), ('B', 'BB'), ('C', 'CC'), ('D', 'DD');

SELECT 
   a.state
   ,a.city
   ,b.state
   ,b.city
FROM tab a
CROSS JOIN tab b
WHERE a.state <> b.state
ORDER BY  a.state, a.city, b.state, b.city

答案 1 :(得分:1)

我认为您需要这样的查询:

SELECT *
FROM Table1 t1
  INNER JOIN
    Table1 t2 ON t1.[state] < t2.[state];

或寻求更好的解决方案:

;WITH t AS(
    SELECT *,
        ROW_NUMBER() OVER (ORDER BY [State]) As rn
    FROM Table1)
SELECT *
FROM t t1
    INNER JOIN
    t t2 ON t1.rn < t2.rn;