在连接中获取Sum并按查询分组

时间:2013-11-15 15:47:49

标签: sql

我正在查询我的在线商店,我正在使用一个小组并通过查看产品delivery_format字段来计算DVD订单的订单数量。

以下是查询:

SELECT 
      account_asset.product_group_id,
      product_group.product_code,
      product_group.name,
      product_group.conference_year,
      product_group.delivery_format,
      product_group.id,
      count(*) AS myCount
  FROM account_asset
  INNER JOIN product_group ON product_group.id = account_asset.product_group_id
  GROUP BY account_asset.product_group_id
  ORDER BY product_group.conference_year,
         product_group.product_code,
         myCount

如何在'myCount'字段中获得总和?

2 个答案:

答案 0 :(得分:0)

从该结果集中选择:

select sum (mycount)
from
(select 
account_asset.product_group_id,
product_group.product_code, 
product_group.name,
product_group.conference_year,
product_group.delivery_format,
product_group.id,
count(*) as myCount
from account_asset 
inner join product_group ON product_group.id = account_asset.product_group_id
group by account_asset.product_group_id 
order by product_group.conference_year,product_group.product_code,myCount) T1

答案 1 :(得分:0)

仅供参考:您不能通过别名来订购,就像您尝试使用ORDER BY MyCount一样。见下面的更正。

关于你的问题,我假设你想要每行的总数。所以这样做:

SELECT account_asset.product_group_id,
       product_group.product_code,
       product_group.name,
       product_group.conference_year,
       product_group.delivery_format,
       product_group.id,
       count(1) AS myCount,
       SUM((SELECT COUNT(1) FROM account_asset INNER JOIN product_group ON product_group.id = account_asset.product_group_id)) AS MyTotal
FROM account_asset
INNER JOIN product_group
    ON product_group.id = account_asset.product_group_id
GROUP BY account_asset.product_group_id
ORDER BY product_group.conference_year,
         product_group.product_code,
         count(1)

但是,在存储过程中定义变量要好得多,因为上面的内容可能会重新计算每一行(检查查询计划)。

所以,在sproc中这样做:

DECLARE @Total = (SELECT COUNT(1) FROM account_asset INNER JOIN product_group ON product_group.id = account_asset.product_group_id)

SELECT account_asset.product_group_id,
       product_group.product_code,
       product_group.name,
       product_group.conference_year,
       product_group.delivery_format,
       product_group.id,
       count(1) AS myCount,
       @Total AS myTotal
FROM account_asset
INNER JOIN product_group
    ON product_group.id = account_asset.product_group_id
GROUP BY account_asset.product_group_id
ORDER BY product_group.conference_year,
         product_group.product_code,
         count(1)

另外......如果你想让它更有效,可以将计算总数的查询更改为半连接而不是连接。即。使用相关的子查询。它的速度要快得多,因为您所做的只是检查product_group中是否存在account_asset。

     SELECT COUNT(1)
     FROM account_asset a WHERE EXISTS (SELECT 1 FROM product_group p WHERE p.id = a.product_group_id)