日期:2014-05-18 浏览次数:20596 次
SELECT dbo.Categories.CategoryName, dbo.Products.ProductName, SUM(CONVERT(money, (dbo.[Order Details].UnitPrice * dbo.[Order Details].Quantity) * (1 - dbo.[Order Details].Discount) / 100) * 100) AS ProductSales FROM dbo.Categories INNER JOIN dbo.Products ON dbo.Categories.CategoryID = dbo.Products.CategoryID INNER JOIN dbo.Orders INNER JOIN dbo.[Order Details] ON dbo.Orders.OrderID = dbo.[Order Details].OrderID ON dbo.Products.ProductID = dbo.[Order Details].ProductID WHERE (dbo.Orders.ShippedDate BETWEEN '19970101' AND '19971231') GROUP BY dbo.Categories.CategoryName, dbo.Products.ProductName
SELECT dbo.Categories.CategoryName, dbo.Products.ProductName, SUM( --10 CONVERT( MONEY, (dbo.[Order Details].UnitPrice*dbo.[Order Details].Quantity) *(1- dbo.[Order Details].Discount)/100 )*100 ) AS ProductSales FROM dbo.Categories --1 INNER JOIN dbo.Products --3 ON dbo.Categories.CategoryID = dbo.Products.CategoryID --2 INNER JOIN dbo.Orders --7 INNER JOIN dbo.[Order Details] --5 ON dbo.Orders.OrderID = dbo.[Order Details].OrderID --6 ON dbo.Products.ProductID = dbo.[Order Details].ProductID --4 WHERE (dbo.Orders.ShippedDate BETWEEN '19970101' AND '19971231') --8 GROUP BY dbo.Categories.CategoryName, dbo.Products.ProductName --9
------解决方案--------------------
SQL Select语句完整的执行顺序: 1、from子句组装来自不同数据源的数据; 2、where子句基于指定的条件对记录行进行筛选; 3、group by子句将数据划分为多个分组; 4、使用聚集函数进行计算; 5、使用having子句筛选分组; 6、计算所有的表达式; 7、使用order by对结果集进行排序。 另外:一个查询语句各个部分的执行顺序: --8) SELECT (9) DISTINCT (11) <TOP_specification> <select_list> --(1) FROM <left_table> --(3) <join_type> JOIN <right_table> --(2) ON <join_condition> --(4) WHERE <where_condition> --(5) GROUP BY <group_by_list> --(6) WITH {CUBE | ROLLUP} --(7) HAVING <having_condition> --(10) ORDER BY <order_by_list>