我现在正在维护一个很棒的应用程序,其他人写了从一些大型政府遗留系统中挖掘出一些数据。基本上我需要一个查询结果来填充一个gridview,它从Tech Order获取每个零件号,并计算Fedlog表中匹配的零件号。如果没有找到,那么请查看“商业”表。现有查询目前仅在Fedlog表中查找,内容如下:
select p.*,
(select case when count(*) > 0 then 'Y' else 'N' end as SL
from tbl_fedlog where [Part Number] = p.[Part Number]) as SL
from tbl_pcms p
where p.[Tech Order] = '0B-E0C-9' order by p.Figure, p.[Index], p.Indenture
当'N'时,我必须查看商业表格。我可以就最好的方法提出一些建议吗?
答案 0 :(得分:1)
“N”情景的结果应该是什么 - 只是另一个“Y”/“N”答案?如果是这样,您应该能够简单地将“N”表达式替换为针对“商业”表的另一个标量查询。
答案 1 :(得分:0)
这是Fedlog查询和商业查询之间的UNION ALL
,它检查每个查询是否存在:
SELECT p.*
, SL = 'Y'
, part_count = (SELECT COUNT(*) FROM tbl_fedlog WHERE [Part Number] = p.[Part Number])
from tbl_pcms p
where p.[Tech Order] = '0B-E0C-9'
AND EXISTS(SELECT 1 FROM tbl_fedlog WHERE [Part Number] = p.[Part Number])
UNION ALL
SELECT p.*
, SL = 'Y'
, part_count = (SELECT COUNT(*) FROM tbl_commercial WHERE [Part Number] = p.[Part Number])
from tbl_pcms p
where p.[Tech Order] = '0B-E0C-9'
AND EXISTS(SELECT 1 FROM tbl_commercial WHERE [Part Number] = p.[Part Number])
AND NOT EXISTS(SELECT 1 FROM tbl_fedlog WHERE [Part Number] = p.[Part Number])
我需要更多信息来解决其他答案中提到的'N'场景。
答案 2 :(得分:0)
如果逻辑是在'Y'
或Fedlog
表格中存在该部分时显示Commercial
,否则'N'
,则可以尝试分组&分别聚合这些表并将(聚合的)聚合结果集加入tbl_pcms
,如下所示:
SELECT
p.*,
CASE WHEN COALESCE(f.PartCount, c.PartCount) IS NULL THEN 'N' ELSE 'Y' END AS SL
FROM tbl_pcms p
LEFT JOIN (
SELECT
[Part Number],
COUNT(*) AS PartCount
FROM tbl_fedlog
GROUP BY [Part Number]
) f ON p.[Part Number] = f.[Part Number]
LEFT JOIN (
SELECT
[Part Number],
COUNT(*) AS PartCount
FROM tbl_commercial
GROUP BY [Part Number]
) c ON p.[Part Number] = c.[Part Number]
WHERE p.[Tech Order] = '0B-E0C-9'
ORDER BY
p.Figure,
p.[Index],
p.Indenture