简体   繁体   中英

Why group by requires all non aggregate columns

In sql, this query has invalid syntax:

select country,city, sum(income) from table1 group by country.

Because the group by expects country and city, not just country. But why is this the case? Because it is possible that I want the result to be grouped by country only. So in below table:

country   city            income

canada    toronto          100
canada    montreal          100
us        LA               200
us        NY               300

If I want to output:

country   city           sum( income)

canada    toronto          200
canada    montreal          200
us        LA               500
us        NY               500

What should be my group by clause?

if you are using Sql Server you can do this

select 
  country,
  city, 
  sum(income) over (partition by country)
from 
  table1 

Or if you are using another database you can use a sub query

  select 
      t1.country,
      t1.city, 
      (select sum(t2.income) from table1 t2 where t1.country = t2.country)
    from 
      table1 t1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM