How to get list of values in GROUP_BY clause?

2019-01-22 12:51发布

If I have data like this in a table

id   data
--   ----
1    1
1    2
1    3
2    4
2    5
3    6
3    4

How do I get results like this in a query (on sybase server)?

id   data
--   ----
1    1, 2, 3
2    4, 5
3    6, 4

9条回答
Rolldiameter
2楼-- · 2019-01-22 13:06

I know that in MySQL there is GROUP_CONCAT and in Sybase I think it's LIST as stated in another answer:

SELECT id, LIST(data||', ')
FROM yourtable
GROUP BY id
查看更多
该账号已被封号
3楼-- · 2019-01-22 13:07

For PostgreSQL, using a similar function string_agg.

SELECT id, string_agg(data, ',')
FROM yourtable
GROUP BY id
查看更多
forever°为你锁心
4楼-- · 2019-01-22 13:10

You can't do this in a straight GROUP BY in plain-vanilla SQL. You have to use a cursor (or a similar construct) to concatenate the values in each group manually.

  • Oracle lets you define a custom aggregator which would do this concatenation in PL/SQL.
  • SQL Server lets you define a custom aggregator in .NET which would do this, as well.
  • I'm not sure about what options Sybase has for defining custom aggregators, though.
查看更多
Anthone
5楼-- · 2019-01-22 13:11

It's been a few years since I've tried using the syntax and I no longer have access to an iAnywhere instance, but there was an aggregate function (list) to do such a task. I cannot confirm if LIST() is still supported.

SELECT id,
       LIST(data)
FROM   table
GROUP BY id
查看更多
戒情不戒烟
6楼-- · 2019-01-22 13:16

Try this one:

SELECT id,
       GROUP_CONCAT(data)
FROM   table
GROUP BY id
查看更多
祖国的老花朵
7楼-- · 2019-01-22 13:19

In MsSQL you can use a function (Don't know if there is somenthing similar in SyBase)

CREATE FUNCTION [dbo].[GetDataForID]
(
    @ID int
)
RETURNS varchar(max)
AS
BEGIN
    declare @output varchar(max)
    select @output = COALESCE(@output + ', ', '') + data
    from table
    where ID = @ID

    return @output
END
GO

And then:

SELECT ID, dbo.GetDataForID(ID) as Data
FROM Table
GROUP BY ID
查看更多
登录 后发表回答