SQL products/productsales

杀马特。学长 韩版系。学妹 提交于 2019-12-02 09:43:52
 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 )

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
)

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