I am trying to perform a SQL query in SQL Server.
What is correct syntax for pulling from data from two tables using a value from the first table to query the second table?
Can I extract a string of text from the first table column and use to query second table. If so, is the syntax I have correct?
Any advice is appreciated. Thanks.
I have posted the code and my notes below. I replaced actual table names with tableA
and tableB
to make it easier to read/understand.
/* Select what we need from tableA */
SELECT
sku, sku_desc, whse_code, create_stamp, stg_pm_f_id as a
FROM
tableA
WHERE
DATEDIFF(day,create_stamp,GETDATE()) < 365
AND stg_status = 5
Select from tableB
using key value extracted from text string within stg_pm_f_id
from tableA
.
The owner_muid column contains stg_pm_f_id
as
wms|stg_pm_f|WHSE1|885563
with elements separated by vertical bar, the last element is what we need to query tableB
, i.e. 885563
.
Example:
select
column_name, group_by_key
from
tableB
where
column_name is not null
and owner_muid like '%885563%'
order by
create_stamp desc
SELECT
column_name, group_by_key
FROM
tableB
WHERE
column_name IS NOT NULL
AND owner_muid LIKE RIGHT(A.stg_pm_f, CHARINDEX('|', (REVERSE(A.stg_pm_f_id))) - 1) /*locate the last vertical bar and grab everything to the right*/
ORDER BY
create_stamp DESC
Display the final results as one row:
a.sku, a.sku_desc, a.whse_code, a.create_stamp, b.column_name, b.group_by_key
I am getting various errors depending on how I configure, but basically I don't know enough SQL yet to execute the command as desired and hoping someone can educate me, thanks.