Select multiple columns from a table, but group by one

后端 未结 11 1445
逝去的感伤
逝去的感伤 2020-12-12 14:54

The table name is \"OrderDetails\" and columns are given below:

OrderDetailID || ProductID || ProductName || OrderQuantity

I\'m trying to s

11条回答
  •  长情又很酷
    2020-12-12 15:16

    I had a similar problem to the OP. Then I saw the answer from @Urs Marian which helped a lot. But additionally what I was looking for is, when there are multiple values in a column and they will be grouped, how I can get the last submitted value (e.g. ordered by a date/id column).

    Example:

    We have following table structure:

    CREATE TABLE tablename(
        [msgid] [int] NOT NULL,
        [userid] [int] NOT NULL,
        [username] [varchar](70) NOT NULL,
        [message] [varchar](5000) NOT NULL
    ) 
    

    Now there are at least two datasets in the table:

    +-------+--------+----------+---------+
    | msgid | userid | username | message |
    +-------+--------+----------+---------+
    |     1 |      1 | userA    | hello   |
    |     2 |      1 | userB    | world   |
    +-------+--------+----------+---------+
    

    Therefore following SQL script does work (checked on MSSQL) to group it, also if the same userid has different username values. In the example below, the username with the highest msgid will be shown:

    SELECT m.userid, 
    (select top 1 username from table where userid = m.userid order by msgid desc) as username,
    count(*) as messages
    FROM tablename m
    GROUP BY m.userid
    ORDER BY count(*) DESC
    

提交回复
热议问题