表订单
订单id 购买单位
1 a
2 b
3 c表订单产品表
订单产品id 订单id 产品名称 产品数量 已发货数量
1 1 xxx 10 0
2 1 yyy 15 0
3 2 xxx 10 0
4 2 yyy 15 5
5 3 xxx 10 10
6 3 yyy 15 15
想查到如下结果
订单id 购买单位 订单状态
1 a 未发货
2 b 发货中
3 c 已发货
订单id 购买单位
1 a
2 b
3 c表订单产品表
订单产品id 订单id 产品名称 产品数量 已发货数量
1 1 xxx 10 0
2 1 yyy 15 0
3 2 xxx 10 0
4 2 yyy 15 5
5 3 xxx 10 10
6 3 yyy 15 15
想查到如下结果
订单id 购买单位 订单状态
1 a 未发货
2 b 发货中
3 c 已发货
4 2 yyy 15 5
=========================
只要 已发货数量>0 and 已发货数量<产品数量 就算是“发货中”?
已发货数量=0 就是“未发货”?
go
create table 表订单
(
订单id int,
购买单位 nvarchar(100)
)
insert into 表订单
select 1, 'a'
union all
select 2, 'b'
union all
select 3, 'c'
go
create table 表订单产品表
(
订单产品id int identity(1,1),
订单id int,
产品名称 nvarchar(100),
产品数量 int,
已发货数量 int
)
insert into 表订单产品表
select 1, 'xxx', 10, 0
union all
select 1, 'yyy', 15, 0
union
select 2, 'xxx', 10, 0
union all
select 2, 'yyy', 15, 5
union all
select 3, 'xxx', 10, 10
union all
select 3, 'yyy', 15, 15
go
select 订单id,购买单位,
case when not exists(select * from 表订单产品表 b where a.订单id=b.订单id and 产品数量<>已发货数量) then '已发货'
when exists(select * from 表订单产品表 b where a.订单id=b.订单id and 产品数量<>已发货数量 and 已发货数量>0) then '正在发货'
else
'未发货'
end
from dbo.表订单 a order by 订单id
-->Microsoft SQL Server Management Studio Complete 2008***
-->AUTHOR : Mr wang **********
-->CREATE TIME : 2010-11-22 08:46:33 **************
-->*******************************************************
--> 测试数据:订单
if object_id('订单') is not null
drop table 订单
GO
---->建表
create table 订单([订单id] int,[购买单位] varchar(1))
insert 订单
select 1,'a' union all
select 2,'b' union all
select 3,'c'
--> 测试数据:产品表
if object_id('产品表') is not null
drop table 产品表
GO
---->建表
create table 产品表([订单产品id] int,[订单id] int,[产品名称] varchar(3),[产品数量] int,[已发货数量] int)
insert 产品表
select 1,1,'xxx',10,0 union all
select 2,1,'yyy',15,0 union all
select 3,2,'xxx',10,0 union all
select 4,2,'yyy',15,5 union all
select 5,3,'xxx',10,10 union all
select 6,3,'yyy',15,15GO
SELECT a.订单id,a.购买单位,case when sum(产品数量)>0 and sum(已发货数量) = 0 then '未发货'
when sum(产品数量)-sum(已发货数量) = 0 then '已发货'
when sum(产品数量)-sum(已发货数量) > 0 and sum(已发货数量)<>0 then '发货中' end as '订单状态'
FROM 订单 a join 产品表 b
on a.订单id = b.订单id
group by a.订单id,a.购买单位
drop table [dbo].[CPDD]
GOif exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DD]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[DD]
GOCREATE TABLE [dbo].[CPDD] (
[CPID] [numeric](18, 0) NULL ,
[ID] [numeric](18, 0) NULL ,
[CPMC] [char] (10) COLLATE Chinese_PRC_CI_AS NULL ,
[CPSL] [numeric](18, 0) NULL ,
[YFHSL] [numeric](18, 0) NULL
) ON [PRIMARY]
GOCREATE TABLE [dbo].[DD] (
[ID] [numeric](18, 0) NULL ,
[DW] [char] (10) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
CREATE function f_pdfh(@id numeric(18,0)) returns varchar(20)
as
begin
if not exists(select * from cpdd where yfhsl>0 and id = @id)
begin
return '未发货'
end
if exists(select * from cpdd where yfhsl>0 and yfhsl<cpsl and id = @id)
begin
return '发货中'
end
return '已发货'endselect id,dw,dbo.f_pdfh(id) as fhzt from dd