id depid 
1   49
2   49
3   49
4   50
5   50
我想得到
49   1,2,3
50   4,5
  
sql 语句如何写?

解决方案 »

  1.   

    select depid,group_concat(id) from tbname group by depid;
      

  2.   

    mysql ?
    select depid,group_concat(id) from tbname group by depid;
      

  3.   

    group_concat
    其相反函数是find_in_set
      

  4.   


    --> 数据库版本:
    --> Microsoft SQL Server 2008 (RTM) - 10.0.1600.22
    --> 测试数据:[TB]
    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[TB]') 
    AND type in (N'U')) 
    DROP TABLE [TB]
    GO---->建表
    create table [TB]([name] varchar(4),[status] varchar(8))
    insert [TB]
    select '小张','普通员工' union all
    select '小张','组长' union all
    select '小二','经理' union all
    select '小三','老板' union all
    select '小三','员工'
    GO
    SELECT a.name,
    status =stuff((
    select ','+convert(varchar(20),status) FROM [TB] WHERE name = a.name  for xml path(''))
    ,1,1,'')
    FROM [TB] a 
    group by a.nameSELECT   a.name,
    status =STUFF(REPLACE(REPLACE(
    (select status
    FROM [TB]  
    where name = a.name  
    FOR XML AUTO
    ), '<TB status="', ','), '"/>', ''), 1, 1, '') 
    FROM [TB] a 
    group by a.name  
    --> 查询结果
    SELECT * FROM [TB]
    --> 删除表格
    --DROP TABLE [TB]
      

  5.   

    mysql> select * from t_a6633281;
    +------+-------+
    | id   | depid |
    +------+-------+
    |    1 |    49 |
    |    2 |    49 |
    |    3 |    49 |
    |    4 |    50 |
    |    5 |    50 |
    +------+-------+
    5 rows in set (0.05 sec)mysql>
    mysql> select depid,group_concat(id)
        -> from t_a6633281
        -> group by depid;
    +-------+------------------+
    | depid | group_concat(id) |
    +-------+------------------+
    |    49 | 1,2,3            |
    |    50 | 4,5              |
    +-------+------------------+
    2 rows in set (0.09 sec)mysql>