检查是否找到特定记录,然后找到具有相同组的另一条记录

时间:2015-03-25 03:34:57

标签: sql-server

我有一张桌子

主表

PROBLEM_ID  PROBLEM            PGROUP
1           Other Hardware     Hardware
2           Error On hardware  Hardware
3           PM                 Hardware
4           Service            Maintenance

和细节

TERM          PROBLEM            PROBLEM_ID
S1G166901     PM                    3
S1G166902     PM                    3
S1G166903     Service               4
S1G166902     Other on hardware     1
S1G166901     Service               4
S1G166901     Other Hardware        1
S1G166901     Error on Hardware     2

我需要查询PROBLEM_ID =' 41'然后找到PROBLEM ='硬件'

PGROUP 像这样

TERM          PROBLEM            PROBLEM_ID    PGROUP
S1G166901     PM                    3          Hardware
S1G166901     Other hardware        1          Hardware             
S1G166901     Error on hardware     2          Hardware
S1G166902     PM                    3          Hardware
S1G166902     Other Hardware        1          Hardware

我尝试使用外部申请,但它返回太多行

我的具体结果是,如果他们不包含PROBLEM_ID =' 41'然后不会显示,但如果包含将显示所有问题与pgroup ='硬件'按术语

我试试这个

SELECT p.TERM, p.Problem_ID,p.problem, PGROUP
FROM Problem_log AS p 
CROSS APPLY ( 
            SELECT s.pgroup, s.problem_id 
            FROM problem AS s 
            WHERE   s.problem_id = p.problem_id AND PGROUP = 'Hardware'  )as s

            WHERE  exists (Select s.PGROUP,s.PROBLEM_ID 
            from PROBLEM_LOG 
            WHERE problem_log.PROBLEM_ID = '41'  GROUP BY term) 
            ORDER BY TERM

我的序列是 - 从problem_log =' 41'

的表problem_log中选择数据
  • 如果problem_ID =' 41'然后对于每个记录检查发现其他问题(仅限硬件)

3 个答案:

答案 0 :(得分:2)

我认为此查询应该适用于您的情况。

Select DISTINCT  D.TERM, M.PROBLEM, M.PROBLEM_ID, M.PGROUP
From Problem M Inner Join Problem_log D
ON M.PROBLEM=D.PROBLEM
WHERE (D.TERM IN (Select TERM FROM Problem_log D1 Inner Join Problem M1
                  ON M1.PROBLEM=D1.PROBLEM
                  Where D1.PROBLEM_ID=D.PROBLEM_ID And 
                        M1.PGROUP='Hardware' AND D1.Problem='PM'))
ORDER BY TERM,PROBLEM

您可以在 fiddle

上尝试此查询

答案 1 :(得分:0)

您只需要使用INNER JOIN和Master表为每个问题IS

获取GROUP

检查以下查询:

SELECT D.TERM, D.PROBLEM, D.PROBLEM_ID, M.PGROUP
FROM Details D INNER JOIN Master M ON D.ProblemID = M.ProblemID
WHERE EXISTS (SELECT * FROM Details WHERE PRoblem = 'PM' AND TERM = D.TERM)

答案 2 :(得分:0)

你能试试吗

SELECT dt.Term, dt.Problem, dt.ProblemID
FROM DetailsTable dt
JOIN MasterTable mt ON dt.ProblemID = mt.ProblemID
JOIN MasterTable mt1 ON mt.PGroup = mt1.PGroup and mt1.Problem = 'PM'
ORDER BY dt.Term