在sql查询中添加Count列

时间:2012-05-30 14:04:54

标签: c# sql sql-server-2008

我有两个名为Production and 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 

请指教。非常感谢!

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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

答案 2 :(得分: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