sql为每一行添加额外的行

时间:2015-06-24 04:08:10

标签: sql sql-server tsql sql-server-2012

是否可以根据字段值向选定的集添加其他行?

我有这个问题:

WITH CTEDivisions AS
(
    SELECT ....
)

SELECT 
    cnt,
    Division
FROM CTEDivisions

返回:

  cnt         Division
  1           Sales
  2           Marketing
  1           Business
  2           IT
  etc...

我需要的是一个在cnt = 2时返回3行的语句,如:

 Division     NewDivision
 Sales        Sales
 Marketing    Marketing - X
 Marketing    Marketing - Y
 Marketing    Marketing - Z
 Business     Business
 IT           IT - X
 IT           IT - Y
 IT           IT - Z
 etc...

我已经搜索了这样做的方法,并使用cursorWHILE循环找到了一些可能的解决方案,但这些解决方案似乎与{ {1}}陈述。

2 个答案:

答案 0 :(得分:4)

为您的额外行创建一个表(作为CTE或永久表)并使用您的条件(cnt=2)保持联接:

DECLARE @T TABLE(cnt int, Division varchar(100));
INSERT INTO @T(cnt, Division) VALUES
(1, 'Sales'),
(2, 'Marketing'),
(1, 'Business'),
(2, 'IT');

WITH
CTEDivisions
AS
(
    SELECT
        cnt
        ,Division
    FROM @T
)
,CTE_Extra
AS
(
    SELECT ' - X' AS Extra
    UNION ALL
    SELECT ' - Y' AS Extra
    UNION ALL
    SELECT ' - Z' AS Extra
)
SELECT
    cnt
    ,Division
    ,Division + ISNULL(Extra, '') AS NewDivision
FROM
    CTEDivisions
    LEFT JOIN CTE_Extra ON CTEDivisions.cnt = 2
;

结果集

cnt    Division    NewDivision
1      Sales       Sales
2      Marketing   Marketing - X
2      Marketing   Marketing - Y
2      Marketing   Marketing - Z
1      Business    Business
2      IT          IT - X
2      IT          IT - Y
2      IT          IT - Z

答案 1 :(得分:4)

WITH CTEDivisions AS
(
    SELECT ....
)

SELECT 
    c.cnt,
    c.Division,
    c.Division + ISNULL(' - ' + o.v, '') AS NewDivision
FROM CTEDivisions c
OUTER APPLY(SELECT v FROM(VALUES('X'),('Y'),('Z'))t(v) WHERE c.cnt = 2)o