我从讲师那里得到了一个测试,我必须制作一个包含3列的表:prodName
,Qty
和totSalesToDate
。列Qty
显示在输入日期已售出的产品数量,totSalesToDate
表示产品在月初销售至输入日期。以下是示例结果表:
prodName | Qty | totSalesToDate
Car | 2 | 10
Bicycle | 8 | 22
Truck | 1 | 7
Motor-cycle | 3 | 12
我必须使用没有子查询的存储过程(TSQL)来创建此表。到目前为止,我提出的问题是:
create procedure SalesReport @date varchar(10)
as
select p.prodName, sum(s.Qty) as Qty
from PeriodTime pt full join Sales s on pt.Time = s.Time full join Product p on s.prodID = p.prodID
where @date = pt.Date
group by p.prodName
union
select p.prodName, sum(s.Qty) as totSalesToDate
from PeriodTime pt full join Sales s on pt.Time = s.Time full join Product p on s.prodID = p.prodID
where pt.Date between '2010060' and @date and p.prodName is not null
group by p.prodName
go
但我得到的结果是这样的:
prodName | Qty
Car | 2
Car | 10
Bicycle | 8
Bicycle | 22
Truck | 1
Truck | 7
Motor-cycle | 3
Motor-cycle | 12
有人可以帮忙吗?我一直在谷歌搜索,但仍然找不到答案。感谢。
答案 0 :(得分:0)
怎么样
create procedure SalesReport @date varchar(10)
as
select p.prodName,
SUM(CASE WHEN @date = pt.Date THEN s.Qty ELSE 0 END) as Qty,
SUM(CASE WHEN pt.Date between '2010060' and @date THEN s.Qty ELSE 0.0 END) AS totSalesToDate
from PeriodTime pt full join Sales s on pt.Time = s.Time full join Product p on s.prodID = p.prodID
group by p.prodName
go