如何从逗号分隔的列表中创建多个记录

时间:2019-12-27 16:31:09

标签: sql-server tsql

我正在使用SQL Server 2019来分隔逗号分隔的值列表。

我有一个看起来像下面的表格

enter image description here

我想对产生和输出的表运行查询,如下所示:

enter image description here

从我阅读StackOverflow的内容来看,没有一个内置函数可以像我想的那样分隔逗号。但是,我看到交叉应用了String_Split这个我认为可能有用的函数,但是我只能在单个列上使用它。

表结构如下:

CREATE TABLE neighbourhoods3.dbo.timeslots 
(
     year VARCHAR(50) NULL,
     time_of_day VARCHAR(50) NULL,
     day_of_week VARCHAR(50) NULL,
     month VARCHAR(50) NULL,
     season VARCHAR(50) NULL,
     public_holiday VARCHAR(50) NULL,
     public_holiday_minus_1 VARCHAR(50) NULL
) ON [PRIMARY]
GO

2 个答案:

答案 0 :(得分:0)

遗憾的是,尽管SQL Server现在支持string_split(),但它不能保证返回集的顺序。

因此,我建议使用另一种方法,例如递归CTE。这是代码示例的示例:

with cte as (
      select convert(varchar(max), NULL) as year,
             convert(varchar(max), NULL) as time_of_day,
             convert(varchar(max), NULL) as day_of_week,
             convert(varchar(max), year) as year_rest,
             convert(varchar(max), time_of_day) as time_of_day_rest,
             convert(varchar(max), day_of_week) as day_of_week_rest
      from t
      union all
      select convert(varchar(max), left(year_rest, charindex(',', year_rest + ',') - 1)) as year,
             convert(varchar(max), left(time_of_day_rest, charindex(',', time_of_day_rest + ',') - 1)) as time_of_day,
             convert(varchar(max), left(day_of_week_rest, charindex(',', day_of_week_rest + ',') - 1)) as day_of_week,
             stuff(year_rest, 1, charindex(',', year_rest + ','), '') as year_rest,
             stuff(time_of_day_rest, 1, charindex(',', time_of_day_rest + ','), '') as time_of_day_rest,
             stuff(day_of_week_rest, 1, charindex(',', day_of_week_rest + ','), '') as day_of_week_rest
      from cte
      where year_rest <> ''
     )
select year, time_of_day, day_of_week
from cte
where year is not null;

Here是db <>小提琴。

答案 1 :(得分:-1)

SELECT GROUP_CONCAT(timeslots.year) as year,GROUP_CONCAT(timeslots.time_of_day) as time_of_day 
FROM `timeslots` 
WHERE 1 
GROUP BY year 

这里GROUP_CONCAT取决于按年份划分的公用列,该列也曾经用逗号(,)分隔。试试这个