我的数据库中有一个表,该表具有一组位值列。我想在逗号分隔的字符串中插入新列,具体取决于这些位列的值。
让我们说一下这些列的名称:
c1,c2,c3,c4
如果一列中的值等于1,我想包含映射的字符串,如下所示:
c1: 'campaign1'
c2: 'campaign2'
c3: 'campaign3'
c4: 'campaign4'
因此,例如,如果一行包含以下值:
c1 = 1, c2 = 0, c3 = 1, c4 = 0
我想在名为“广告系列”的新列中插入以下内容
'campaign1,campaign3'
关于如何实现此目标的任何建议?
答案 0 :(得分:3)
我将使用stuff()
和一些字符串操作来做到这一点:
select t.*,
stuff( ((case when c1 = 1 then ',campaign1' else '' end) +
(case when c2 = 1 then ',campaign2' else '' end) +
(case when c3 = 1 then ',campaign3' else '' end) +
(case when c4 = 1 then ',campaign4' else '' end)
), 1, 1, ''
) as campaigns
from t;
答案 1 :(得分:0)
这可行,但可能不是最佳解决方案:
DECLARE @table TABLE (id INT, c1 INT, c2 INT, c3 INT, c4 INT);
INSERT INTO @table
SELECT 1, 1, 0, 1, 0
UNION ALL
SELECT 2, 0, 0, 1, 1;
WITH cte AS (
SELECT
id,
CASE WHEN c1 = 1 THEN 'campaign1,' ELSE '' END +
CASE WHEN c2 = 1 THEN 'campaign2,' ELSE '' END +
CASE WHEN c3 = 1 THEN 'campaign3,' ELSE '' END +
CASE WHEN c4 = 1 THEN 'campaign4,' ELSE '' END AS campaigns
FROM
@table)
SELECT
id,
CASE
WHEN LEN(campaigns) > 0 THEN LEFT(campaigns, LEN(campaigns) - 1)
ELSE ''
END AS campaigns
FROM
cte;
Gordon击败了我使用STUFF
方法,当我意识到这种方法更好时,我匆忙编写了该方法,但这是一个答案,它也显示了UPDATE
可能如何工作,因为这是您最初的方法要求:
DECLARE @table TABLE (id INT, c1 INT, c2 INT, c3 INT, c4 INT, campaigns VARCHAR(512));
INSERT INTO @table
SELECT 1, 1, 0, 1, 0, NULL
UNION ALL
SELECT 2, 0, 0, 1, 1, NULL;
UPDATE
t
SET
campaigns = STUFF(CASE WHEN c1 = 1 THEN ',campaign1' ELSE '' END +
CASE WHEN c2 = 1 THEN ',campaign2' ELSE '' END +
CASE WHEN c3 = 1 THEN ',campaign3' ELSE '' END +
CASE WHEN c4 = 1 THEN ',campaign4' ELSE '' END, 1, 1, '')
FROM
@table t;
SELECT * FROM @table;
结果:
id c1 c2 c3 c4 campaigns
1 1 0 1 0 campaign1,campaign3
2 0 0 1 1 campaign3,campaign4
答案 2 :(得分:0)
您可以使用IIF函数(前提是您使用的是 SQL Server 2012 + ),如下所示:
select IIF(c1=1, 'Campaign1', '')+IIF(c2=1 and c1>0,',','')+
IIF(c2=1, 'Campaign2', '')+IIF(c3=1 and c1+c2>0,',','')+
IIF(c3=1, 'Campaign3', '')+IIF(c4=1 and c1+c2+c3>0,',','')+
IIF(c4=1, 'Campaign4', '') as 'Campaigns'
from tab t;
答案 3 :(得分:0)
只需给出另一个选择,您可以使用concat并替换掉
DECLARE @table TABLE (id INT, c1 INT, c2 INT, c3 INT, c4 INT)
INSERT INTO @table
SELECT 1, 1, 0, 1, 0 UNION ALL SELECT 2, 0, 0, 1, 1
select t.*,
replace(replace(c1, '1', 'Campaing1,'), '0', '') +
replace(replace(c2, '1', 'Campaing2,'), '0', '') +
replace(replace(c3, '1', 'Campaing3,'), '0', '') +
replace(replace(c4, '1', 'Campaing4,'), '0', '')
from @table t
结果是
id c1 c2 c3 c4 COLUMN1
-- -- -- -- -- -------
1 1 0 1 0 Campaing1,Campaing3,
2 0 0 1 1 Campaing3,Campaing4,
但是我会去找戈登的答案