How to use group by in SQL Server query?

前端 未结 5 1211
死守一世寂寞
死守一世寂寞 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 16:51

    When you group then you can select only the columns you group by. Other columns need to be aggrgated. This can be done with functions like min(), avg(), count(), ...

    Why is this? Because with group by you make multiple records unique. But what about the column not being unique? The DB needs a rule for those on how to display then - aggregation.

    0 讨论(0)
  • 2020-12-10 16:51

    You need to apply aggregate function such as max(), avg() , count() in group by.

    For example this query will sum totalAmount for all moshtari_ID

    select moshtari_ID,sum (totalAmount) from Factors group by moshtari_ID;
    

    output will be

    moshtari_ID    SUM
    2              120000 
    1              200000
    
    0 讨论(0)
  • 2020-12-10 17:01

    If you are applying group clause then you can only use group columns and aggregate function in select

    syntax:

    SELECT expression1, expression2, ... expression_n, 
           aggregate_function (aggregate_expression)
    FROM tables
    [WHERE conditions]
    GROUP BY expression1, expression2, ... expression_n
    [ORDER BY expression [ ASC | DESC ]];
    
    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2020-12-10 17:06

    Try it,

    select * 
    from Factorys
    Group by ID, date, time, factorNo, trackingNo, totalAmount, createAt, updateAt, bark_ID, moshtari_ID
    
    0 讨论(0)
提交回复
热议问题