当前位置: 代码迷 >> Sql Server >> sql 将两个表每条记录均组合一次如何写
  详细解决方案

sql 将两个表每条记录均组合一次如何写

热度:15   发布时间:2016-04-24 10:11:21.0
sql 将两个表每条记录均组合一次怎么写?
也就是表一里有2条记录 表二里有2条记录
组合出结果集有四条记录
例如
table1
a b
1 1
2 2

table2
c d
3 3
4 4
最后组合出
a b c d
1 1 3 3
2 2 3 3
1 1 4 4
2 2 4 4
这要怎么写???
------解决方案--------------------
排个序
----------------------------------------------------------------
-- Author  :DBA_HuangZJ(發糞塗牆)
-- Date    :2014-08-11 10:46:19
-- Version:
--      Microsoft SQL Server 2012 - 11.0.5058.0 (X64) 
-- May 14 2014 18:34:29 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[table1]
if object_id('[table1]') is not null drop table [table1]
go 
create table [table1]([a] int,[b] int)
insert [table1]
select 1,1 union all
select 2,2
--> 测试数据:[table2]
if object_id('[table2]') is not null drop table [table2]
go 
create table [table2]([c] int,[d] int)
insert [table2]
select 3,3 union all
select 4,4
--------------开始查询--------------------------



select * from [table1] a CROSS JOIN [table2] b
ORDER BY c,d
----------------结果----------------------------
/* 
a           b           c           d
----------- ----------- ----------- -----------
1           1           3           3
2           2           3           3
1           1           4           4
2           2           4           4
*/
  相关解决方案