Frage

I've been using CTEs to build some specially formatted tables that I need, this has been working great as long as the data comes from one table or I can join, but now I am presented with a situation in which I don't have any common fields to join on.

Here is the Ideal end-result

+------+---------+
| 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  |
+------+---------+

Here are some sample tables

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')
;

Here is the CTE working with a single table

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

But what I want is something like this... Except when I do this i'm hit with "The multi-part identifier "t1.emp_id" could not be bound"

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

Now, I could do what I have done before, which is make a separate column for each value except this time I am dealing with hundred of values in table2 that I need to insert so that's not practical anymore.

Thanks in advance for any suggestions.

War es hilfreich?

Lösung

Here is how you can get the desired output. But I have the feeling I'm missing the point:

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top