-1

我有以下表格:

  • 订单
  • 产品
  • OrderDetails 作为联合表。

我还有一个连接到产品的类别表;CategoryID 是 Products 的外部表。

我正在尝试获取一个表,其中包含 1997 年、1998 年、季度、以 C 字母开头的类别名称和销售(UDF)之间的订单年份。这是我尝试过的:

Select YEAR(o.OrderDate) AS "Year", DATENAME(Quarter, o.OrderDate) AS "Qtr",
       c.CategoryName,
       dbo.SaleAfterDiscount(od.UnitPrice, od.Quantity, od.Discount) AS "Sale"
  From Orders o, [Order Details] od, Categories c, Products p
 WHERE (YEAR(o.OrderDate)='1997'OR YEAR(o.OrderDate)='1998')
   AND c.CategoryName LIKE 'c%'
   AND od.OrderID = o.OrderID
   AND od.ProductID = p.ProductID
   AND c.CategoryID = p.CategoryID

但我得到了很多结果。如何对它们进行分组或修复查询以获得正确答案?

4

1 回答 1

1
  1. 使用显式 JOIN
  2. 不要在列上使用函数
  3. GROUP BY 所有非聚合列

像这样:

Select
     YEAR(o.OrderDate) AS "Year",
     DATENAME(Quarter, o.OrderDate) AS "Qtr",
     c.CategoryName,
     SUM(dbo.SaleAfterDiscount(od.UnitPrice, od.Quantity, od.Discount)) AS "SaleSum"
From
     Orders o
     JOIN
     [Order Details] od ON od.OrderID=o.OrderID
     JOIN
     Products p ON od.ProductID=p.ProductID
     JOIN
     Categories c ON c.CategoryID=p.CategoryID
WHERE
     o.OrderDate >= '19970101' AND o.OrderDate < '19990101'
     AND
     c.CategoryName LIKE 'c%'
GROUP BY
     YEAR(o.OrderDate),
     DATENAME(Quarter, o.OrderDate),
     c.CategoryName;
于 2013-02-20T09:47:45.067 回答