2013-07-22 43 views
1

我需要加入三张表以告诉产品需要什么文档。并非每件产品都需要所有文件。SQL Group通过加入

有一个文档表,产品表,跟踪与产品相关的文档DocTracking表

 
Product Table 
ProdID ProdName 
1  Ball 
2  Wheel 
 
DocTracking Table 
ProdID  DocID 
1   1 
1   2 
2   2 

我想加入到这个样子:

 
ProdID  ProdName Needs Word Doc? Needs Excel Doc? 
1   Ball  Yes    Yes 
2   Wheel  No     Yes 

任何帮助,将不胜感激,如果我需要使这成为存储过程,这很好。

+1

搜索“数据透视表”在这里SO。你也可以用Case语句来完成。 – Tim

回答

1

如果只有这些文件,它们解决您可以使用此查询:

SELECT ProdID, ProdName,  
     [Needs Word Doc] = CASE WHEN EXISTS(
      SELECT 1 FROM Document d INNER JOIN DocTracking dt ON d.DocID=dt.DocID 
      WHERE dt.ProdID = p.ProdID AND d.[Doc Name] = 'Word Document' 
     ) THEN 'Yes' ELSE 'No' END, 
     [Needs Excel Doc] = CASE WHEN EXISTS(
      SELECT 1 FROM Document d INNER JOIN DocTracking dt ON d.DocID=dt.DocID 
      WHERE dt.ProdID = p.ProdID AND d.[Doc Name] = ' Excel Spreadsheet' 
     ) THEN 'Yes' ELSE 'No' END 
FROM dbo.Product p 

当然你也可以使用DocID,然后查询不依赖于名字。

+0

感谢您的评论。不幸的是,在“现实生活中”大约有20份文件,而且它不是固定的,可能还有更多。 – NwkProg

+0

我现在只想和这个一起去,但如果有人有更好的方法,让我知道。我听说不使用游标,但似乎是一个使用它的时间? – NwkProg

1
select P.ProdID, P.ProdName, 
     case 
      when DW.DocID is null then 'Yes' 
      else 'No' 
     end as NeedsWordDoc,  
     case 
      when DE.DocID is null then 'Yes' 
      else 'No' 
     end as NeedsExcelDoc 
from Product P 
left join DocTracking DTW on DTW.ProdId = P.ProdId 
left join Document DW on DW.DocID = DTW.DocID 
          and DW.Name = 'Word Document' 
left join DocTracking DTE on DTE.ProdId = P.ProdId 
left join Document DE on DE.DocID = DTE.DocID 
          and DE.Name = 'Excel Spreadsheet' 
1

这比典型的数据透视查询稍微复杂一些。但唯一具有挑战性的部分是确定包含哪些文档,然后获取'Yes''No'

以下执行此与coalesce()和条件,对于一种类型的文件的存在检查:

select pt.ProdId, pt.ProdName, 
     coalesce(MAX(case when dt.DocId = 1 then 'Yes' end), 'No') as "Needs Word Doc?", 
     coalesce(MAX(case when dt.DocId = 2 then 'Yes' end), 'No') as "Needs Excel Doc?" 
from ProductTable pt left outer join 
    DocTracking dt 
    on dt.ProdId = dt.ProdId 
group by pt.ProdId, pt.ProdName; 

注意,SQL查询返回的列的固定数量。所以,你不能有一个SQL查询,根据文档表中的内容简单地返回不同数量的列。你可以创建一个字符串中的SQL查询,然后使用特定于数据库的命令来运行它。

0

可能是这会帮助你 - 使用数据透视:

select ProdId, ProdName, 
case when isnull([Word Document],0)<>0 then 'Yes' 
else 'No' 
end as [Needs Word Doc?], 
case when isnull([Excel Spreadsheet],0)<>0 then 'Yes' 
else 'No' 
end as [Needs Excel Spreadsheet?] 
from 
(
select p.ProdId,p.ProdName,d.DocId,d.DocName from 
@Prod p left join 
@Track t 
on p.ProdId=t.ProdId 
inner join @Doc d 
on t.DocId=d.DocId 
) 
as temp 
pivot 
(max(DocID) 
For DocName in ([Word Document],[Excel Spreadsheet]) 
) 
as pvt