16

目前我正在尝试自学更多关于 SQL 的知识,并且目前正在尝试使用SQL Server 2008 数据库中的、SUM和函数执行一些简单的销售报告。我已经设法逐行获取每个组的总数、计数和平均值。COUNTAVGGROUP BY

如何按行获得所有组的总数?

到目前为止的SQL:

SELECT 
    SUM(dbo.tbl_orderitems.mon_orditems_pprice) AS prodTotal,
    AVG(dbo.tbl_orderitems.mon_orditems_pprice) AS avgPrice,
    count(dbo.tbl_orderitems.uid_orditems_prodid) AS prodQty,
    dbo.tbl_orderitems.txt_orditems_pname
FROM 
    dbo.tbl_orderitems
INNER JOIN 
    dbo.tbl_orders 
    ON (dbo.tbl_orderitems.uid_orditems_orderid = dbo.tbl_orders.uid_orders)
WHERE 
    dbo.tbl_orders.uid_order_webid = 
       <cfqueryparam cfsqltype="cf_sql_integer" value="#session.webid#">
    AND dbo.tbl_orders.txt_order_status = 
       <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.sale_status#">
GROUP BY
    dbo.tbl_orderitems.txt_orditems_pname
产品数量总平均  

韦斯特伯里攀爬架 17 8,023.00 471.94
Sandpoint 豪华攀爬架 34 36,146.00 1,063.12
Roseberry 攀爬架 9 7,441.00 826.78
Ridgeview Texas 攀爬架 10 6,990.00 699
塞尔伍德野餐桌 9 489.92 54.44

我需要 qty 列和 Gross 列的总计

非常感谢

杰森

4

3 回答 3

25

您正在寻找ROLLUP运算符,它将在结果集的末尾添加一个总计行。如果您正在寻找更复杂的汇总总计,请使用带有 GROUP BY 子句的 ROLLUP 或 CUBE,例如 @MartinSmith 或Aggregation WITH ROLLUP提供的链接

SELECT 
    SUM(dbo.tbl_orderitems.mon_orditems_pprice) AS prodTotal,
    AVG(dbo.tbl_orderitems.mon_orditems_pprice) AS avgPrice,
    count(dbo.tbl_orderitems.uid_orditems_prodid) AS prodQty,
    dbo.tbl_orderitems.txt_orditems_pname
FROM 
    dbo.tbl_orderitems
INNER JOIN 
    dbo.tbl_orders ON (dbo.tbl_orderitems.uid_orditems_orderid = dbo.tbl_orders.uid_orders)
WHERE 
    dbo.tbl_orders.uid_order_webid = <cfqueryparam cfsqltype="cf_sql_integer" value="#session.webid#">
    AND dbo.tbl_orders.txt_order_status = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.sale_status#">
GROUP BY
    dbo.tbl_orderitems.txt_orditems_pname
WITH ROLLUP
于 2012-04-29T11:00:05.347 回答
6

我知道这是一个老问题,但仅供将来参考 - 您还可以通过使用 GROUPING SETS 来更好地控制分组过程。例如:

SELECT 
    SUM(dbo.tbl_orderitems.mon_orditems_pprice) AS prodTotal,
    AVG(dbo.tbl_orderitems.mon_orditems_pprice) AS avgPrice,
    count(dbo.tbl_orderitems.uid_orditems_prodid) AS prodQty,
    COALESCE(dbo.tbl_orderitems.txt_orditems_pname, 'TOTAL')
FROM 
    dbo.tbl_orderitems
INNER JOIN 
    dbo.tbl_orders 
    ON (dbo.tbl_orderitems.uid_orditems_orderid = dbo.tbl_orders.uid_orders)
WHERE 
    dbo.tbl_orders.uid_order_webid = 
       <cfqueryparam cfsqltype="cf_sql_integer" value="#session.webid#">
    AND dbo.tbl_orders.txt_order_status = 
       <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.sale_status#">
GROUP BY GROUPING SETS (
    (dbo.tbl_orderitems.txt_orditems_pname),
    ()
)

这样,结果将两行都按 txt_orditems_pname 分组,并且根本没有分组。您可以指定更多的分组集,即。查询一个部门和团队的平均工资,还返回了部门和整个公司的总和。

于 2015-02-13T07:06:35.310 回答
1

将您的选择包装在另一个选择中并总结列。

于 2012-04-29T10:25:36.793 回答