一种常见的(我假设?)查询类型:
我有两个表('products'、'productsales')。“productsales”中的每条记录都代表一次销售(因此它有“date”、“quantity”、“product_id”)。我如何有效地进行如下查询:
检索在日期 Y 和日期 Z 之间销售超过 X 次的所有产品的产品名称。
(X 是销售数量而不是交易数量)
一种常见的(我假设?)查询类型:
我有两个表('products'、'productsales')。“productsales”中的每条记录都代表一次销售(因此它有“date”、“quantity”、“product_id”)。我如何有效地进行如下查询:
检索在日期 Y 和日期 Z 之间销售超过 X 次的所有产品的产品名称。
(X 是销售数量而不是交易数量)
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 )
上面的查询并不完全正确......
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
)
实际上,我认为您应该通过语句来学习分组
最简单的说法是:
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
使用MS AdventureWorks DB成功测试,使用以下 -
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