SQL逗号从多列中分离列表

时间:2009-10-21 20:05:05

标签: sql sql-server sql-server-2005

我的数据如下:

CUSTOMER_ID  OPERDAYSJUL  OPERDAYSAUG  OPERDAYSSEP ... OPERDAYSJUN
1            30           15           2
2            5            1            0
3            6            0            12
4            12           5            23

对于每个customer_id,我想要一个以逗号分隔的列表,指明客户在哪些月份运营:

CUSTOMER_ID  OPERATING_MONTHS
1            Jul, Aug, Sep
2            Jul, Aug
3            Jul, Sep
4            Jul, Aug, Sep

等等。我如何使用SQL Server 2005 SQL(而不是T-SQL)轻松生成这个以逗号分隔的列表?

我在Stack Overflow和其他地方看到的大多数解决方案似乎都是基于连接多个行值而不是列值创建逗号分隔列表:

  • T-SQL
  • FOR XML PATH('')
  • 相关子查询与REPLACE / STUFF / SUBSTRING相结合

我错过了一些明显的东西吗?在此先感谢您的帮助或指向适当的现有解决方案。

5 个答案:

答案 0 :(得分:4)

这剥去了额外的逗号

SELECT 
  CUSTOMER_ID,
  SUBSTRING(
    CASE WHEN OPERDAYSJUL > 0 THEN ', Jul' ELSE '' END +
    CASE WHEN OPERDAYSAUG > 0 THEN ', Aug' ELSE '' END +
    ...
    CASE WHEN OPERDAYSJUN > 0 THEN ', Jun' ELSE '' END,
   3, 255)
FROM TheTable

答案 1 :(得分:2)

declare @t table (CUSTOMER_ID int
  , OPERDAYSJUL int
  , OPERDAYSAUG int
  , OPERDAYSSEP int
  -- ... rest of 9 months here
  );

insert into @t (CUSTOMER_ID, OPERDAYSJUL, OPERDAYSAUG, OPERDAYSSEP)
select 1, 30, 15, 22 union all
select 2, 0, 10, 10 union all
select 3, 0, 0, 10 union all
select 4, 0, 0, 0 union all
select 5, 10, 0, 10 union all
select 6, 10, 10, 0 union all
select 7, 0, 10, 0 union all
select 8, 10, 0, 0;    

with cte_months as (
select CUSTOMER_ID
  , case when OPERDAYSJUL=0 then '' else ', Jul' end 
  + case when OPERDAYSAUG=0 then '' else ', Aug' end
  + case when OPERDAYSSEP=0 then '' else ', Sep' end
  -- ... rest of 9 months here
  as month_list
 from @t)
 select CUSTOMER_ID, substring(month_list, 3, 70) 
 from cte_months;

答案 2 :(得分:1)

假设你的表有13列(一年中每个月有1列+ CUSTOMER_ID),你可以这样写:

SELECT 
  CUSTOMER_ID,
  CASE OPERDAYSJUL > 0 THEN 'Jul,' ELSE '' END +
  CASE OPERDAYSAUG > 0 THEN 'Aug,' ELSE '' END +
  ...
FROM MyTable

并使用CASE语句构建一个代表逗号分隔列表的字符串,每月一个。

答案 3 :(得分:1)

你可以这样做。

CONCAT(CASE OPERDAYSJUL > 0 THEN "Jul," ELSE "" END,CASE OPERDAYSAUG > 0 THEN "Aug" ELSE "" END ... )

答案 4 :(得分:0)

select 
   customer_id,
   case when len(operating_month) > 0 then 
       left(operating_month, len(operating_month) - 1)
   else 
       operating_month 
   end as operating_month
from
(
   SELECT CUSTOMER_ID,  
   CASE OPERDAYSJUL > 0 THEN 'Jul,' ELSE '' END 
   +  CASE OPERDAYSAUG > 0 THEN 'Aug,' ELSE '' END 
   +  ... 
   as operating_month
   FROM MyTable
) as x