【问题标题】:Sql Server - Using a CTE combining values from multiple tables without joiningSql Server - 使用 CTE 组合来自多个表的值而不加入
【发布时间】:2014-03-24 20:40:32
【问题描述】:

我一直在使用 CTE 来构建一些我需要的特殊格式的表,只要数据来自一个表或者我可以加入,这一直很好用,但现在我遇到了一种情况,我不需要'没有任何共同的领域可以加入。

这是理想的最终结果

+------+---------+
| p_id | value   | 
+------+---------+
| 1    | 1,55556 |
| 2    | 2,1212  |
| 3    | 2,6868  |
| 4    | 2,4545  |
| 5    | 1,55557 |
| 6    | 2,1212  |
| 7    | 2,6868  |
| 8    | 2,4545  |
+------+---------+

这里有一些示例表

CREATE TABLE Table1
 ([Emp_ID] varchar(10))
;

INSERT INTO Table1
 ([Emp_ID])
VALUES
 (55556), 
 (55557)
;

CREATE TABLE Table2
 ([Type] Varchar(10), [Type_ID] varchar(10))
;

INSERT INTO Table2
 ([Type], [Type_ID])
VALUES
 ('Black', '1212'),
 ('Red', '6868'),
 ('Orange', '4545')
;

这是使用单个表的 CTE

GO
WITH cte as (
    SELECT t1.[emp_id], C.Value
    FROM table1 t1
        outer apply (values
            ('1,' + t1.[emp_id])
       ) as C(Value)
)

SELECT
    row_number() over(order by [emp_id], value) as p_id,
    value
FROM cte

但我想要的是这样的......除非我这样做,否则我会遇到“无法绑定多部分标识符“t1.emp_id””

GO
WITH cte as (
    SELECT t1.[emp_id], C.Value
    FROM table1 t1, table2 t2
        outer apply (values
            ('1,' + t1.[emp_id]),
            ('2,' + t2.type_id)
       ) as C(Value)
)

SELECT
    row_number() over(order by [emp_id], value) as p_id,
    value
FROM cte

现在,我可以做我以前做过的事情,即为每个值创建一个单独的列,除了这次我要处理 table2 中需要插入的数百个值,因此这不再实用了。

提前感谢您的任何建议。

【问题讨论】:

    标签: sql-server-2008 common-table-expression


    【解决方案1】:

    以下是获得所需输出的方法。但我觉得我错过了重点:

    with cte as
    (
      select '2,'+type_id as value, emp_id
      from table1 t1, table2 t2
    
      union all
    
      select '1,'+emp_id as value, emp_id
      from table1  
    )
    select value,
      row_number() over(order by emp_id, value) as p_id
    from cte
    

    【讨论】:

    • 就是这样!我不知道我可以在不写段落的情况下传达我正在做的事情,但这完全完成了我想要做的事情,基本上我试图输出一个文本文件,其中包含 employee_id 作为第一项,然后是每个在这 2 个中,项目在他们的配置文件中定义了一些被导入的东西。这很有帮助,谢谢汤姆!
    猜你喜欢
    • 2019-10-05
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    相关资源
    最近更新 更多