Sql complex group query

I have a table with the following rows:

id. type  - link 

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

I want to group the type (image) by date so that they appear as a single line. In this example, the first two images are combined together and the output will look like this:

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://..
+3
source share
4 answers
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
+1
source

With MySQL, you can do this:

SELECT id, type, group_concat(link) 
FROM table
GROUP BY id, type
+1
source
select id, type, group_concat(link) from table

.

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 MySQLs GROUP_CONCAT() SQL Server 2005

0

Source: https://habr.com/ru/post/1717315/


All Articles