Using SUM() without grouping the results

后端 未结 4 1840
别那么骄傲
别那么骄傲 2020-12-03 10:34

I already read (this), but couldn\'t figure out a way to implement it to my specific problem. I know SUM() is an aggregate function and it doesn\'t make sense n

相关标签:
4条回答
  • 2020-12-03 10:56

    This does just one sum() query, so it should perform OK:

    SELECT a.id, b.amount
    FROM table1 a
    cross join (SELECT SUM(amount) as amount FROM table1 AS amount) b
    
    0 讨论(0)
  • 2020-12-03 10:58

    With MS SQL you can use OVER()

     select id, SUM(amount) OVER()
     from table1;
    
    select id, SUM(amount) OVER()
    from (
      select 1 as id, 23 as amount
      union all
      select 2 as id, 11 as amount
      union all
      select 3 as id, 8 as amount
      union all
      select 4 as id, 7 as amount
    ) A
    

    --- OVER PARTITION ID
    

    PARTITION BY which is very useful when you want to do SUM() per MONTH for example or do quarterly reports sales or yearly... (Note needs distinct it is doing for all rows)

     select distinct id, SUM(amount) OVER(PARTITION BY id) as [SUM_forPARTITION]
     from (
         select 1 as id, 23 as amount
         union all
         select 1 as id, 23 as amount
         union all
         select 2 as id, 11 as amount
         union all
         select 2 as id, 11 as amount
         union all
         select 3 as id, 8 as amount
         union all
         select 4 as id, 7 as amount
    ) OverPARTITIONID
    

    0 讨论(0)
  • 2020-12-03 11:05

    Join the original table to the sum with a subquery:

    SELECT * FROM table1, (SELECT SUM(amount) FROM table1 AS amount) t
    
    0 讨论(0)
  • 2020-12-03 11:07
    SELECT a.id, b.amount
    FROM table1 a
    CROSS JOIN
    (
        SELECT SUM(amount) amount FROM table1
    ) b
    

    You need to perform a cartesian join of the value of the sum of every row in the table to each id. Since there is only one result of the subselect (49), it basically just gets tacked onto each id.

    0 讨论(0)
提交回复
热议问题