How to Sum multiple lines in sql

后端 未结 8 1766
猫巷女王i
猫巷女王i 2020-12-11 12:16

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

相关标签:
8条回答
  • 2020-12-11 12:36
    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;
    
    0 讨论(0)
  • 2020-12-11 12:39
    SELECT Company_Name, Company_ID, sum(Amount)
    FROM your table
    GROUP BY Company_Name, Company_ID
    
    0 讨论(0)
  • 2020-12-11 12:39

    Try this;

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

    Demo here.

    0 讨论(0)
  • 2020-12-11 12:39

    Worked for me:

        select Company_Name   , Company_ID   ,sum(Amount) as 'Amount' from Company group by 
    Company_Name,Company_ID   ;
    
    0 讨论(0)
  • 2020-12-11 12:41
    create table #tempTable
    (
        Id bigint,
        Title varchar(100),
        Amount money
    )
    insert into #TempTable(Title,Id,Amount)
    Values
    ('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)
    
    
    select Title, Sum(Amount)Amount from #TempTable
    group by Title,ID
    
    drop Table #TempTable
    
    0 讨论(0)
  • 2020-12-11 12:42

    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
    
    0 讨论(0)
提交回复
热议问题