转换重型asp代码以在sql中运行

时间:2013-06-20 11:46:54

标签: sql optimization asp-classic

上下文中的一些asp代码;时间表产品的销售业绩基于产品在线的起始年份到活跃的年数,例如2000年发布的产品将具有几年的销售高峰,但到2004年将没有...但是代码这个适用于系统中的所有产品并按年分组...(如果您有疑问我可以回答它们,或者我认为查看代码会对其正在做的事情提供一个合理的建议!!)

首先,它运行此查询以获取数据(我想要更改):

    SELECT Products.ProductID, Products.AnticipatedSalesPattern, Convert(Char(10),Invoices.Date,103) As [date], Orders.Cost 
FROM (Orders INNER JOIN Products ON Orders.ProductID = Products.ProductID) 
INNER JOIN Invoices ON Orders.Invoice = Invoices.InvoiceNum 
WHERE (Products.IsResource=1 AND Orders.Returned<>1 AND Orders.Cost<>0) 
ORDER BY Products.ProductID, Invoices.Date;

以下是处理数据的方式(在asp中),我知道它只是使样本建模数据变得无效......

while not dbrecords.eof
    RecordsCount = RecordsCount + 1
if dbrecords("ProductID") <> LastPID then
    PIDsCount = PIDsCount + 1
    LastPID = dbrecords("ProductID")
    FirstSaleDate = dbrecords("Date")
    if month(FirstSaleDate) < 9 then
        FirstSchoolYear = Year(FirstSaleDate) - 1
    else
        FirstSchoolYear = Year(FirstSaleDate)
    end if
end if
YearsSinceFirstSale = int(DateDiff("d",FirstSaleDate,dbrecords("Date"))/365)
MyArray(FirstSchoolYear-2000,YearsSinceFirstSale) = MyArray(FirstSchoolYear-2000,YearsSinceFirstSale) + dbrecords("Cost")
MyArrayTotals(FirstSchoolYear-2000) = MyArrayTotals(FirstSchoolYear-2000) + dbrecords("Cost")
TotalSales = TotalSales + dbrecords("Cost")
dbrecords.movenext
wend

现在我喜欢的是删除将数据放入数组的整个过程以及返回年度数据的查询

我真正坚持的是写sql以通过自首次销售以来的年份并跟踪每个产品(如何在sql中实现),我通过CTE语句接受参数......

此外,如果您认为这可以通过其他方式实现,那将是非常有效的

非常感谢任何帮助......

到目前为止我到了;

这不提供asp生成的相同数据...并且还让我知道是否有更好的方法来做到这一点......

DROP VIEW inline_view;

GO

CREATE VIEW inline_view AS
  SELECT p2.ProductID, p2.AnticipatedSalesPattern, Invoices.Date, Orders.Cost, case when MONTH(date) < 9 then YEAR(date)-1 else YEAR(date) end   as year, 

  (select top 1 case when MONTH(i.date) < 9 then YEAR(i.date)-1 else YEAR(i.date) end from Invoices i inner join Orders o on i.InvoiceNum=o.Invoice
    inner join Products p on o.ProductID = p.ProductID where p2.ProductID = p.productID order by i.Date asc)  as startsale

FROM (Orders INNER JOIN Products p2 ON Orders.ProductID = p2.ProductID) 
INNER JOIN Invoices ON Orders.Invoice = Invoices.InvoiceNum 
WHERE (p2.IsResource=1 AND Orders.Returned<>1 AND Orders.Cost<>0)
;

GO

SELECT * FROM (
select SUM(cost) sum, datediff(y, startsale, year) as year, startsale  from inline_view 
group by year, startsale
) as data

PIVOT
(
    sum(sum)
--years after product is online
    FOR year IN ([1], [2], [3],[4],[5],[6],[7],[8],[9], [10],[11], [12])
) as pvt;

0 个答案:

没有答案