我需要加入三个表格,以便了解产品需要哪些文件。并非每个产品都需要所有文件。
有一个 Document 表、一个 Product 表和一个 DocTracking 表,用于跟踪与产品关联的文档
产品表 产品 ID 产品名称 1 球 2轮
文档跟踪表 产品编号 DocID 1 1 1 2 2 2
我希望加入看起来像这样:
ProdID ProdName 需要 Word Doc?需要 Excel 文档吗? 1 球 是 是 2 轮 否 是
任何帮助将不胜感激,如果我需要把它变成一个存储过程,那很好。
我需要加入三个表格,以便了解产品需要哪些文件。并非每个产品都需要所有文件。
有一个 Document 表、一个 Product 表和一个 DocTracking 表,用于跟踪与产品关联的文档
产品表 产品 ID 产品名称 1 球 2轮
文档跟踪表 产品编号 DocID 1 1 1 2 2 2
我希望加入看起来像这样:
ProdID ProdName 需要 Word Doc?需要 Excel 文档吗? 1 球 是 是 2 轮 否 是
任何帮助将不胜感激,如果我需要把它变成一个存储过程,那很好。
如果您只有这些文档并且它们已修复,则可以使用此查询:
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, 那么查询不依赖于名字。
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'
这比典型的数据透视查询要复杂一些。但是,唯一具有挑战性的部分是确定包含哪些文档,然后获取'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 查询,然后使用特定于数据库的命令来运行它。
可能这会帮助你 - 使用枢轴:
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