How to Sum multiple lines in sql

走远了吗. 提交于 2019-12-17 20:30:54

问题


I have multiple lines of data all sharing the same Company id.

Is there a way to 'sum' all the amounts to give me one line of data per company id using SQL Server Management Studio 2005?

For example I currently have the below data......

Company_Name   Company_ID   Amount
Company 6         10024   120
Company 6         10024   569
Company 6         10024    53
Company 6         10024   100
Company 6         10024   564
Company 7         10638  9500
Company 7         10638   105
Company 7         10638   624

What i would like to try and get is.......

Company_ Name   Company_ID     Amount 
Company 6        10024         1406
Company 7        10638        10229

Is there a way of doing this?

Any advice pointing me the right way would be great.

Thanks,


回答1:


SELECT Company_Name, Company_ID, SUM(Amount) 
FROM TableName GROUP BY Company_Name, Company_ID



回答2:


SELECT Company_Name, Company_ID, sum(Amount)
FROM your table
GROUP BY Company_Name, Company_ID



回答3:


Try this;

SELECT Company_Name, Company_ID, SUM(Amount) AS Amount
FROM Companies
GROUP BY Company_Name, Company_ID;

Demo here.




回答4:


SELECT Company_Name, Company_ID, sum(Amount)
FROM table
group by Company_Name, Company_ID



回答5:


You need to use GROUP BY and SUM function.

SELECT Company_Name, Company_ID, SUM(Amount) AS TOTAL_AMOUNT
FROM myTable
GROUP BY Company_Name, Company_ID



回答6:


WITH T ( Company_Name, Company_ID, Amount )
     AS
     (
      SELECT 'Company 6', '10024', 120 UNION ALL
      SELECT 'Company 6', '10024', 569 UNION ALL
      SELECT 'Company 6', '10024', 53 UNION ALL
      SELECT 'Company 6', '10024', 100 UNION ALL
      SELECT 'Company 6', '10024', 564 UNION ALL
      SELECT 'Company 7', '10638', 9500 UNION ALL
      SELECT 'Company 7', '10638', 105 UNION ALL
      SELECT 'Company 7', '10638', 624 
     )
SELECT DISTINCT Company_Name, Company_ID, 
       SUM(Amount) OVER (PARTITION BY Company_ID) AS total_amount
  FROM T;



回答7:


Worked for me:

    select Company_Name   , Company_ID   ,sum(Amount) as 'Amount' from Company group by 
Company_Name,Company_ID   ;


来源:https://stackoverflow.com/questions/9600587/how-to-sum-multiple-lines-in-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!