如何嵌套WHILE LOOP

时间:2014-10-15 22:42:58

标签: sql

我遇到麻烦这些WHILE循环。我希望我的查询查看每个Product_ID,并计算它到达后的前12天每天购买的次数。根据日期,季节等,库存项目在20,000到140,000种不同的库存中变化很大。我想显示day01 [该PiD已售出的COUNT],day02等。我在想一个嵌套循环可能是答案,但是我愿意接受建议......建议?

注意:现在查询似乎已经破解并且永远运行。   请原谅形成。

              DECLARE
    @Item_Num01 int,
    @Item_Num02 int,
    @Nomenclature varchar(255),
    @PiD varchar(255),
    @MadeOn datetime,
    @TimeSpan int,   
    @date datetime,
    @count int

           SELECT * FROM TABLE_02 ORDER BY ItemName ASC


    SET @Item_Num01 = 1
    SELECT @Item_Num02 = MAX(INVEN_ID) FROM TABLE_02
    CREATE TABLE TABLE_03(ItemName nvarchar(255), Prod_ID varchar(255), Shipped_Date datetime, 
    Time_Span int, Day int, OrdersCount int, INVEN_ID int)

    WHILE @Item_Num01 <= @Item_Num02
BEGIN
           SET @Nomenclature = 0
    SET @PiD = 0
    SET @MadeOn = 0
    SET @TimeSpan = 0
    SET @count = 0

    SELECT @Nomenclature = ItemName FROM TABLE_02 WHERE INVEN_ID = @Item_Num01
    SELECT @PiD = Product_ID FROM TABLE_02 WHERE INVEN_ID = @Item_Num01
    SELECT @MadeOn = Shipped_Date FROM TABLE_02 WHERE INVEN_ID = @Item_Num01
    SELECT @TimeSpan = Time_Span FROM TABLE_02 WHERE INVEN_ID = @Item_Num01
        SET @date = @MadeOn
       WHILE @date < DATEADD(DAY,12,@MadeOn)
    BEGIN
    SELECT @count = COUNT(INV_STK.Product_ID)
    FROM INV_STK
        WHERE INV_STK.PRODUCT_ID = @PiD
        AND CONVERT(DATE,SoldDate) = CONVERT(DATE,@date)

    INSERT INTO TABLE_03
    VALUES (@Nomenclature, @PiD, @MadeOn, @TimeSpan,DATEDIFF(dd,@MadeOn,@date+@TimeSpan, @count, @Item_Num01)

    SET @date = DATEADD(DAY,1,@date)
 END
    SET @Item_Num01 = @Item_Num01 + 1
  END

SELECT * FROM TABLE_03 ORDER BY INVEN_ID, Day ASC

谢谢

1 个答案:

答案 0 :(得分:0)

如果没有实际的样本数据,我就会想到这一点:

SELECT t.ItemName, t.Product_ID AS Prod_ID, t.Shipped_Date, t.Time_Span, d.NumDays AS [Day], count(i.Product_ID) AS OrdersCount, t.INVEN_ID
FROM table_02 t
    CROSS JOIN (
        SELECT NumDays
        FROM (
            SELECT ROW_NUMBER()OVER(ORDER BY name) NumDays
            FROM master..spt_values
            ) a
        WHERE NumDays <= 12
    ) d
    LEFT JOIN INV_STK i ON i.Product_ID = t.Product_ID
        and CONVERT(DATE,i.SoldDate) = CONVERT(DATE,DATEADD(DAY,d.NumDays,t.Shipped_Date))
GROUP BY t.ItemName, t.Product_ID, t.Shipped_Date, t.Time_Span, d.NumDays, t.INVEN_ID

基本上,您希望确保所有12天,所以生成具有内部联接的人工行,并使用dateadd函数中的日期值来左边连接到库存表。之后,它进行了所有聚合和分组。这应该服务于你的目的。不过,我还需要样本输入和所需输出来进一步细化。