简体   繁体   中英

Select * with one Group By Column in SQL

I want to select * from a table and group by only one column. I am new to SQL, so a basic questions. My query looks like this.

Select top 10
    [DocumentClass], [DocumentUID]
    ,[DocumentClassification]
    ,[DocumentNumber]
    ,[Revision]
    ,[Description]
    ,[Owner]
from 
    Table
Group BY 
    [DocumentClass]

Error I am getting:

Column 'DocumentUID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Please advise. Thanks

If you want to get one row per document class, then use row_number() instead of group by :

Select top 10 t.*
from (select t.*, row_number() over (partition by documentclass order by newid()) as seqnum
      from table t
     ) t
where seqnum = 1;

row_number() is a function that enumerates the rows. In this case, each document class will start over. newid() is just a way of choosing a random row.

Normally, when you use group by , you would also have aggregation functions such as min() or sum() .

This error means the SQL Server doesn't know which column do you want to use. When you use GROUP BY command you want to select one specific value ( MIN, SUM, or AVG) or u want all ( count that rows ) . You get all necessary information from this site. GROUP BY

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