[sql server] 问题总结4 - 标准笛卡尔积

来源:互联网 发布:喀秋莎软件介绍 编辑:程序博客网 时间:2024/06/05 07:31

我有两个表:1.商品大类表t_spda,主要字段:大类编号dlbh,比如有三个大类5000,,5001,5002。
  2.销售类别表t_xslb,主要字段:销售类别xslb(比如有三类1,2,3),类别折扣率lbzk(比如对应为0.7,0.8,0.9)
我要写的sql语句是表t_spda的每一条记录对应表t_xslb的所用记录,即具体显示如下:
5000 1 0.7
5000 2 0.8
5000 3 0.9
5001 1 0.7
5001 2 0.8
5001 3 0.9
5002 1 0.7
5002 2 0.8
5002 3 0.9

---------------------------------

 

create table a(id int,ic int)
insert into a
select 1,5000 union all
select 2,5001
go

create table b(ig decimal(6,2))
insert into b
select 6.1 union all
select 6.11
go
--1
select *
from a,b
--2
select *
from a cross join b

drop table a,b

 

---------------------------------------

 

也可以再 保准的笛卡尔积 上面加些条件,得到想要的结果

 

例如

 

现有产品信息表,包括Item_No,Item_Name两个字段,如下:
Item_No Item_Name
001 MainABC
002 MainEFG
003 ABC
004 EFG

根据Item_Name判断是否有子物料,有就显示到后面两列,
上表中可以看出:003为001的子物料,004为002的子物料,

希望得到如下结果:
Item_No Item_Name Part_No PartName
001 MainABC 003 ABC  
002 MainEFG 004 EFG
求SQL语句
因现在数据量比较大,求速度快点的语句
-----------------------

 

if object_id('Product') is not null drop table Product
create table Product (Item_no varchar(10), ItemName varchar(10))
--写数据
insert into Product
select '001','MainABC' union all
select '002','MainEFG' union all
select '003','ABC' union all
select '004','EFG'

select * from  Product a ,Product b  where  charindex(b.ItemName,a.ItemName)>1

 

 

----------------------------------

 

 

一张表 t 字段 team
'a'
'b',
'c',
'd'
任意组合
结果

a,b
a,c
a,d
b,c
b,d
c,d
怎么写

 

create table t(team varchar(1))
insert into t values('a')
insert into t values('b')
insert into t values('c')
insert into t values('d')
go

select m.team , n.team from t m, t n where m.team < n.team

drop table t

/*
team team
---- ----
a    b
a    c
b    c
a    d
b    d
c    d

(所影响的行数为 6 行)


*/