组concat值与其他行分开,作为sql查询中的名称

时间:2017-08-27 04:41:52

标签: php mysql sql

 SELECT GROUP_CONCAT(`flim_category_name` SEPARATOR '*') 
`flim_category_name`,country, GROUP_CONCAT(`flim_video` SEPARATOR '*') flim_video,
  GROUP_CONCAT(`flim_video_images` SEPARATOR '*') flim_video_images FROM 
  flim_management_table GROUP BY `country` limit 0,1

在这个查询中,我得到了像这样的表结构

flim_category_name    country     flim_video                                       flim_video_images
Guru*Mersal*Aadi      India    ww.com,ww.com,ww.com* ww.com,ww.com,ww.com* ,,,     217953157.jpg,,,,,,,,,*,,,,,,,,,

我需要使用start来分隔,而不是像这样单独的行

flim1 flim2   flim3    country     flim_video1             flim_video2        flim_video3   images1        image2     image 3
Guru  Mersal   Aadi      India    ww.com,ww.com,ww.com  ww.com,ww.com,ww.com       ,,,    217953157.jpg,,,  ,,,,,     ,,,,,

我需要像这样构建表格。

2 个答案:

答案 0 :(得分:0)

在Oracle中,我能想到的最好的就是这个。

 WITH f AS
(
       SELECT 'Ghajini'             film_category_name ,
              'INDIA'               country ,
              'IMG1.jpg,iMAGE2.JPG' flim_images,
              'WW.COM,WW.COM,WW.COM' flim_url 
       FROM   dual
       UNION ALL
       SELECT 'dIWALE'              film_category_name ,
              'INDIA'               country ,
              'IMG1.jpg,iMAGE2.JPG' flim_images,
              'WW.COM,WW.COM'       flim_url
       FROM   dual
       UNION ALL
       SELECT 'gURU'                film_category_name ,
              'SOUTH AFRICA'        country,
              'IMG1.jpg,iMAGE2.JPG' flim_images,
              'WW.COM,WW.COM'       flim_url
       FROM   dual ), f2 AS
(
         SELECT   f.* ,
                  Row_number() over (PARTITION BY country ORDER BY ROWNUM ) rn
         FROM     f ), f3 AS
(
         SELECT   Listagg(film_category_name,',') within GROUP ( ORDER BY ROWNUM ) over ( PARTITION BY country ) film_category_name ,
                  country ,
                  flim_images,
                  flim_url,
                  rn
         FROM     f2 )
SELECT *
FROM   f3 pivot ( max(flim_images) AS flim_images_row  ,
                  max(flim_url)    AS flim_url FOR rn IN (1,2) ) p
ORDER BY film_category_name;

输出是这样的:

FILM_CATEGORY_NAME    COUNTRY           1_FLIM_IMAGES_ROW    1_FLIM_URL             2_FLIM_IMAGES_ROW   2_FLIM_URL
Ghajini,dIWALE         INDIA            IMG1.jpg,iMAGE2.JPG  WW.COM,WW.COM,WW.COM   IMG1.jpg,iMAGE2.JPG WW.COM,WW.COM
gURU                   SOUTH AFRICA     IMG1.jpg,iMAGE2.JPG  WW.COM,WW.COM   - 

如果您不知道每个country的行数,那么您唯一的选择是使用动态SQL动态生成和执行查询。但是我不推荐它,因为结构和设计对于任何数据提取,您的表都是低效的。您需要重新组织组件并在需要存储和检索有用数据的位置创建单独的表。

答案 1 :(得分:-2)

您可以使用Mysql的group_concat功能:

select group_concat(Film_category_name), Country, group_concat(flim_images),group_concat(flim_url) from table group by country 

对于oracle,请检查:
Is there any function in oracle similar to group_concat in mysql?