How to use group by in SQL Server query?

前端 未结 5 1299
死守一世寂寞
死守一世寂寞 2020-12-10 16:37

I have problem with group by in SQL Server

I have this simple SQL statement:

select * 
from Factors 
group by moshtari_ID

and I get

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-10 17:06

    In general, once you start GROUPing, every column listed in your SELECT must be either a column in your GROUP or some aggregate thereof. Let's say you have a table like this:

    | ID | Name        | City        |
    |  1 | Foo bar     | San Jose    |
    |  2 | Bar foo     | San Jose    |
    |  3 | Baz Foo     | Santa Clara |
    

    If you wanted to get a list of all the cities in your database, and tried:

    SELECT * FROM table GROUP BY City
    

    ...that would fail, because you're asking for columns (ID and Name) that aren't in the GROUP BY clause. You could instead:

    SELECT City, count(City) as Cnt FROM table GROUP BY City
    

    ...and that would get you:

    | City        | Cnt |
    | San Jose    |  2  |
    | Santa Clara |  1  |
    

    ...but would NOT get you ID or Name. You can do more complicated things with e.g. subselects or self-joins, but basically what you're trying to do isn't possible as-stated. Break down your problem further (what do you want the data to look like?), and go from there.

    Good luck!

提交回复
热议问题