0

我从讲师那里得到了一个测试,我必须制作一张桌子,里面有 3 列:prodNameQtytotSalesToDate。列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

有人可以帮忙吗?我一直在谷歌搜索,但仍然找不到答案。谢谢。

4

1 回答 1

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  
于 2013-11-08T09:20:06.743 回答