0

I have two table called Production and Chart as below.

Production

Name Layer
CDV  TSK
CDV  USV
M1   OSK

Chart

Name
L1_CDV_TSK
L1_CDV_TSK
L1_M1_OSK

I have to produce output like this:

Name Layer Count
CDV  TSK    2
CDV  USV    0
M1   OSK    1

// bse L1_CDV_TKK and L1_M1_OSK are in the Charttable.

How could I write a SQL query to achieve this?

This is my attempt, but it cannot see every row in the Prodution table

Select 
    p.Name, p.layer, Count(*) as test
from 
    Production p, Chart c 
where 
    c.chartname like '%'+ p.name+'_'+p.layer + '%'
group by 
    p.Name, p.layer 

Please advise. Thanks a lot!

0

3 Answers 3

5
Select p.Name,p.layer,Count(c.chartname) as test
from Production p
left join Chart c on c.chartname like '%'+ p.name+'_'+p.layer + '%'
group by p.Name,p.layer 

EDIT :

think you have a typo in your "Chart" list, or I don't understand the result you want... (TSK, TKK)

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

Select p.Name,p.layer,Count(*) as test
from Production p
left join Chart c on c.chartname like '%'+ p.name+'_'+p.layer + '%'
group by p.Name,p.layer

Comments

0

First, you need to learn new join syntax:

Select p.Name, p.layer,Count(*) as test
from Production p join
     Chart c
     on c.chartname like '%'+ p.name+'_'+p.layer + '%'
group by p.Name, p.layer

Second, you are filtering out the one with the count of zero.

To get what you want, try:

Select p.Name, p.layer,
       sum(case when c.chartname like '%'+ p.name+'_'+p.layer + '%' then 1 else 0 end) as test
from Production p cross join
     Chart c
group by p.Name, p.layer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.