34,838
社区成员




-->测试数据1: @tabSales
declare @tabSales table (品名 varchar(4),数量 tinyint)
insert into @tabSales
select '白沙',2 union all
select '红梅',5 union all
select '双喜',3 union all
select '中华',6
-->测试数据2: @tabPrice
declare @tabPrice table (品名 varchar(4),包装 varchar(4),单价 numeric(18,2))
insert into @tabPrice
select '白沙','硬盒',5 union all
select '白沙','软盒',4 union all
select '红梅','ALL',5 union all
select '双喜','硬盒',8 union all
select '双喜','软盒',6.5
select
品名,
[单价]=isnull((select top 1 单价 from @tabPrice where 品名=a.品名 order by case when 包装='硬盒' then 1
when 包装='ALL' then 2
when 包装='软盒' then 3 end ),0),
[金额]=isnull((select top 1 单价 from @tabPrice where 品名=a.品名 order by case when 包装='硬盒' then 1
when 包装='ALL' then 2
when 包装='软盒' then 3 end ),0)*数量
from
@tabSales A
(所影响的行数为 4 行)
(所影响的行数为 5 行)
品名 单价 金额
---- -------------------- ------------------------
白沙 5.00 10.00
红梅 5.00 25.00
双喜 8.00 24.00
中华 .00 .00
(所影响的行数为 4 行)
/*
(所影响的行数为 4 行)
(所影响的行数为 5 行)
品名 单价 金额
---- -------------------- ------------------------
白沙 5.00 10.00
红梅 5.00 25.00
双喜 8.00 24.00
中华 .00 .00
(所影响的行数为 4 行)
*/
-->测试数据1: @tabSales
declare @tabSales table (品名 varchar(4),数量 tinyint)
insert into @tabSales
select '白沙',2 union all
select '红梅',5 union all
select '双喜',3 union all
select '中华',6
-->测试数据2: @tabPrice
declare @tabPrice table (品名 varchar(4),包装 varchar(4),单价 numeric(18,2))
insert into @tabPrice
select '白沙','硬盒',5 union all
select '白沙','软盒',4 union all
select '红梅','ALL',5 union all
select '双喜','硬盒',8 union all
select '双喜','软盒',6.5
select
A.品名,
isnull(单价,0) 单价,
isnull(单价,0)*数量 金额
from
@tabSales A
Left join
(select * from @tabPrice where 包装<>'软盒') B
on A.品名=B.品名
CREATE TABLE [tabPrice] (
[品名] [varchar] (50) NULL ,
[包装] [varchar] (50) NULL ,
[单价] [numeric](18, 2) NULL
)
CREATE TABLE [tabSales] (
[品名] [varchar] (50) NULL ,
[数量] [int] NULL
)
insert tabSales (品名,数量)
values ('白沙',2)
insert tabSales(品名,数量)
values ('红梅',5)
insert tabSales(品名,数量)
values ('双喜',3)
insert tabSales(品名,数量)
values ('中华',6)
insert tabPrice(品名,包装,单价)
values ('白沙','硬盒',5)
insert tabPrice(品名,包装,单价)
values ('白沙','软盒',4)
insert tabPrice(品名,包装,单价)
values ('红梅','ALL',5)
insert tabPrice(品名,包装,单价)
values ('双喜','硬盒',8)
insert tabPrice(品名,包装,单价)
values ('双喜','软盒',6.5)
select b.品名,isnull(a.单价,0)单价 ,isnull(a.单价,0)*b.数量 as 金额
from
(
select * from tabprice where 包装<>'软盒'
)a
right join tabsales b
on a.品名=b.品名
/*
品名 单价 金额
-------------------------------------------------- -------------------- -------------------------------
白沙 5.00 10.00
红梅 5.00 25.00
双喜 8.00 24.00
中华 .00 .00
(所影响的行数为 4 行)
*/