E
E
Eytmarin2019-04-29 10:33:31
SQL
Eytmarin, 2019-04-29 10:33:31

Is there any way to optimize this stored procedure?

Is there any way to optimize this stored procedure?

CREATE PROCEDURE  pr_КолебанияСпросаТоваров
@Интервал INT, @ТипРезультата INT, @Имя VARCHAR(50) OUTPUT, @Итог NUMERIC (12,3) OUTPUT
  AS
  DECLARE @Code INT
  IF @ТипРезультата = 1
    SELECT @Code=КодТовара, @Итог=SUM(Количество)
    FROM Заказ
    WHERE ДатаЗаказа BETWEEN GetDate()[email protected]Интервал AND GetDate()
    GROUP BY КодТовара
    ORDER BY SUM(Количество)
  ELSE
    SELECT @Code=КодТовара, @Итог=SUM(Количество)
    FROM Заказ
    WHERE ДатаЗаказа BETWEEN GetDate()[email protected]Интервал AND GetDate()
    GROUP BY КодТовара
    ORDER BY SUM(Количество) DESC
  SELECT @Имя = Наименование
  FROM Товар 
  WHERE КодТовара = @Code
  GO

In particular, this
IF @ТипРезультата = 1
    SELECT @Code=КодТовара, @Итог=SUM(Количество)
    FROM Заказ
    WHERE ДатаЗаказа BETWEEN GetDate()[email protected]Интервал AND GetDate()
    GROUP BY КодТовара
    ORDER BY SUM(Количество)
  ELSE
    SELECT @Code=КодТовара, @Итог=SUM(Количество)
    FROM Заказ
    WHERE ДатаЗаказа BETWEEN GetDate()[email protected]Интервал AND GetDate()
    GROUP BY КодТовара
    ORDER BY SUM(Количество) DESC

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2019-04-29
@Rsa97

SELECT @Code=t1.КодТовара, @Итог=t1.Количество, @Имя=t2.Наименование
  FROM (
    SELECT КодТовара, SUM(Количество) AS Количество
      FROM Заказ
      WHERE ДатаЗаказа BETWEEN GetDate()[email protected]Интервал AND GetDate()
      GROUP BY КодТовара
  ) AS t1
  JOIN Товар AS t2
    ON t2.КодТовара = t1.КодТовара
  ORDER BY t1.Количество * IF(@ТипРезультата = 1, 1, -1)

R
Ruslan., 2019-04-29
@LaRN

Judging by the query:
SELECT @Code=ItemCode, @Total=SUM(Quantity)
FROM Order
WHERE OrderDate BETWEEN GetDate()[email protected] AND GetDate()
GROUP BY ItemCode
ORDER BY SUM(Quantity)
You can return many rows, but this way you read it all into variables, then all the same, only one last value in the sort order will remain, i.e. a product with a maximum or minimum value of SUM(Quantity), i.e. you can try to use an aggregate function on SUM(Quantity).
The query also uses GetDate(), and if we assume that there are no records in the table with a date greater than GetDate(), then we can check for an open range, i.e.
OrderDate >= GetDate()[email protected]
So, you can try this:

WITH Q AS  
(SELECT КодТовара, SUM(Количество) as Сумм
   FROM Заказ
  WHERE ДатаЗаказа >= GetDate()[email protected]Интервал
  GROUP BY КодТовара)
SELECT @Code = Q.КодТовара, 
       @Итог = Q.Сумм
  FROM Q
 WHERE Q.Сумм = (SELECT CASE WHEN @ТипРезультата = 1 
                              THEN MAX(Q.Сумм) 
                              ELSE MIN(Q.Сумм) 
                         END
                   FROM Q)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question