SQL products/productsales

人走茶凉 提交于 2019-12-20 06:42:21

问题


A common (i assume?) type of query:

I have two tables ('products', 'productsales'). Each record in 'productsales' represents a sale (so it has 'date', 'quantity', 'product_id'). How do i efficiently make a query like the following:

Retrieve the product names of all products that were sold more than X times between date Y and date Z.

(X is the quantity sold not the number of transactions)


回答1:


 SELECT p.[name]
 FROM products p
 WHERE p.product_id in (SELECT s.product_id
     FROM productsales s
     WHERE s.[date] between @dateStart and @dateEnd
     GROUP BY s.product_id
     HAVING Sum(s.quantity) > @X )



回答2:


The above query is not entirely correct ...

SELECT Name FROM Products
WHERE ProductId IN
( SELECT ProductId 
  FROM ProductSales
  WHERE ProductSales.Date BETWEEN  Y AND Z 
  GROUP BY ProductId
  HAVING SUM(ProductSales.Qty) > x
)



回答3:


Actually, I think you should learn the group by statement

The simplest statement would be:

SELECT ps.product_id, COUNT(*) 
           FROM product_sales ps 
           WHERE ps.product_id = id AND ps.Date BETWEEN @Y AND @Z
           GROUP_BY product_id;



回答4:


SELECT p.[name]
FROM
products p
INNER JOIN
productsales ps
ON 
p.id = ps.product_id
WHERE
ps.date BETWEEN @Y AND @Z
GROUP BY
p.[name] 
--,p.id if it is likely that you have two products with the same name
HAVING
SUM(ps.quantity) > @X

Tested successfully with MS AdventureWorks DB, using the following-

DECLARE @Y DATETIME, @Z DATETIME, @X INT    

SET @Y = '2004-06-09'
SET @Z = '2004-08-01'
SET @X = 100

    SELECT p.[Name]
    FROM
    Production.Product p
    INNER JOIN
    Sales.SalesOrderDetail ps
    ON 
    p.ProductID = ps.ProductID
    WHERE
    ps.ModifiedDate BETWEEN @Y AND @Z
    GROUP BY p.Name
    HAVING
    SUM(ps.OrderQty) > @X


来源:https://stackoverflow.com/questions/501347/sql-products-productsales

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!