sql:如何获得总和

时间:2016-03-10 05:20:15

标签: sql sum

下面我可以得到sub_shares的结果,但我不知道如何通过使用sub_shares的结果得到结果总和(sub_shares):

怎么办?

SELECT * , 
Client.client_chi_name, 
Client.client_eng_name, 
SUM( shares_no ) AS sub_shares
FROM Shareholder
LEFT OUTER JOIN Client ON Shareholder.client_id = Client.client_id
WHERE Shareholder.com_no = 2040628
GROUP BY Shareholder.client_id
ORDER BY SUM( shares_no ) DESC,
Shareholder.date_of_register DESC

表股东

  • com_no
  • date_of_register
  • share_type
  • class_shares
  • client_id
  • shares_no
  • transferee_id
  • currency
  • shares_amount

非常感谢你的帮助和帮助。支持。

4 个答案:

答案 0 :(得分:0)

SELECT * , 
  Client.client_chi_name, 
  Client.client_eng_name, 
  SUM( shares_no ) AS sub_shares,
  (select sum(shares_no) FROM Shareholder
      LEFT OUTER JOIN Client ON Shareholder.client_id = Client.client_id
      WHERE Shareholder.com_no = 2040628) as sum_of_sum
FROM Shareholder
LEFT OUTER JOIN Client ON Shareholder.client_id = Client.client_id
WHERE Shareholder.com_no = 2040628
GROUP BY Shareholder.client_id
ORDER BY SUM( shares_no ) DESC,
Shareholder.date_of_register DESC

您可以使用subselect

再添加一列

答案 1 :(得分:0)

您可以根据需要使用以下代码,

GROUP BY Shareholder.client_id WITH ROLLUP

GROUP BY Shareholder.client_id WITH CUBE

有关详细信息,请参阅technet

答案 2 :(得分:0)

您可以使用CTE(Commom Table Expression)来完成相同的任务

with cte as
(
SELECT * , 
Client.client_chi_name, 
Client.client_eng_name, 
SUM( shares_no ) AS sub_shares
FROM Shareholder
LEFT OUTER JOIN Client ON Shareholder.client_id = Client.client_id
WHERE Shareholder.com_no = 2040628
GROUP BY Shareholder.client_id
ORDER BY shares_no  DESC,
Shareholder.date_of_register DESC
)

select cte.client_chi_name,cte.client_eng_name,SUM(cte.sub_shares) sub_shares from cte   --you can access more column which is present in * 
GROUP BY client_chi_name,client_eng_name --place extra column yor are accessing

答案 3 :(得分:0)

您可以删除GROUP BY并执行以下操作:

SUM( shares_no ) OVER (PARTITION BY Client.client_id) AS sub_shares
SUM( shares_no ) AS total_shares,

您还需要从SELECT DISTINCT开始,否则您将获得重复项。