0

我有两个名为 Production 和 Chart 的表,如下所示。

生产

Name Layer
CDV  TSK
CDV  USV
M1   OSK

图表

Name
L1_CDV_TSK
L1_CDV_TSK
L1_M1_OSK

我必须产生这样的输出:

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

// bse L1_CDV_TKK and L1_M1_OSK are in the Charttable.

我如何编写 SQL 查询来实现这一点?

这是我的尝试,但它看不到Prodution表中的每一行

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 

请指教。非常感谢!

4

3 回答 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 

编辑 :

认为您的“图表”列表中有错字,或者我不明白您想要的结果......(TSK,TKK)

于 2012-05-30T14:09:09.330 回答
1

试试这个:

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
于 2012-05-30T14:10:29.593 回答
0

首先,您需要学习新的连接语法:

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

其次,您正在过滤掉计数为零的那个。

要获得您想要的,请尝试:

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
于 2012-05-30T14:11:09.373 回答