sql complex group查询

时间:2009-09-10 04:29:41

标签: sql mysql

我有一个包含以下行的表:

id. type  - link 

 1. image - http://1
 2. image - http://2
 3. text  - none
 4. video - http://..
 5. image - http://..
 6. text  - http://..

我想按日期对类型(图像)进行分组,因此它们显示为单行。在此示例中,前两个图像将合并在一起,输出将如下所示:

1. image - http://1, http://2  ** GROUPED BY DATE, if they are same type and not break type after it.
2. text  - none
3. video - http://..
4. image - http://..
5. text  - http://..

4 个答案:

答案 0 :(得分:1)

使用MySQL,你可以这样做:

SELECT id, type, group_concat(link) 
FROM table
GROUP BY id, type

答案 1 :(得分:1)

SELECT  grouper, type, GROUP_CONCAT(link)
FROM    (
        SELECT  @group := @group + (NOT (COALESCE(@type, type) = type)) AS grouper,
                @type := type,
                m.*
        FROM    (
                SELECT  @group := 0,
                        @type := NULL
                ) vars,
                mytable m
        ) q
GROUP BY
        grouper

答案 2 :(得分:0)

select id, type, group_concat(link) from table

试试。

答案 3 :(得分:0)

以下是SQL Server 2005及更高版本的完整思维弯曲等效示例:


create table #Temp
    (GroupField int, ValueType varchar(10), Value varchar(2048))

insert into #Temp (GroupField, ValueType, Value) VALUES (1, 'image', 'http://1')
insert into #Temp (GroupField, ValueType, Value) VALUES (1, 'image', 'http://2')
insert into #Temp (GroupField, ValueType, Value) VALUES (2, 'text', 'none')
insert into #Temp (GroupField, ValueType, Value) VALUES (2, 'video', '30mins')
insert into #Temp (GroupField, ValueType, Value) VALUES (2, 'image', 'http://5')
insert into #Temp (GroupField, ValueType, Value) VALUES (3, 'image', 'http://4')
insert into #Temp (GroupField, ValueType, Value) VALUES (3, 'text', 'hello')
insert into #Temp (GroupField, ValueType, Value) VALUES (3, 'image', 'http://7')
insert into #Temp (GroupField, ValueType, Value) VALUES (4, 'image', 'http://0')

    SELECT GroupField, ValueType,
           LEFT([Values],LEN([Values]) - 1)   AS [Values]
    FROM   (SELECT GroupField, ValueType,
                   (SELECT value + ', ' AS [text()]
                    FROM   #Temp AS internal
                    WHERE  internal.GroupField = GroupFields.GroupField and internal.ValueType = GroupFields.ValueType 
                    FOR xml PATH ('')
                   ) AS [Values]
            FROM   (SELECT  GroupField, ValueType
                    FROM     #Temp
                    GROUP BY GroupField, ValueType) AS GroupFields) AS pre_trimmed;

产生结果:


GroupField   ValueType    Values
1            image        http://1, http://2
2            image        http://5
2            text         none
2            video        30mins
3            image        http://4, http://7
3            text         hello
4            image        http://0

根据您的具体情况,可能需要一些ORDER BY条款......改编自Rational Relational - Emulating MySQL’s GROUP_CONCAT() Function in SQL Server 2005