我一直在尝试以下查询,目标是从A获得结果然后使用来自A(客户编号和部分)的特定信息拉出前几年基于Part的信息。
我一直在尝试不同的变化,但无法让它发挥作用。
思想?
Select * from Table A
where CODE = 'YYY' and Year (END_DATE)> '2015' OR
Part like 'Z%' AND plan like '5%' and Year (END_DATE)> '2015'
)AS A
WHERE (EXISTS
(SELECT * from ( Select * from Table B) as B
WHERE B.Part = A.PArt
AND B.CUST_NUM = A.CUST_NUM
AND YEAR(B.Start_date) = YEAR(A.Start_Date) - 1 )
答案 0 :(得分:0)
您可以执行以下操作。
Select * from Table A
where ( CODE = 'YYY' and Year (END_DATE)> '2015' ) OR
(Part like 'Z%' AND plan like '5%' and Year (END_DATE)> '2015')
WHERE EXISTS
(SELECT * from table B WHERE B.Part = A.PArt
AND B.CUST_NUM = A.CUST_NUM
AND YEAR(B.Start_date)=YEAR(A.Start_Date) - 1 )
如果存在AND OR两者,则将条件置于paranthesis
答案 1 :(得分:0)
--You can simplify your query like it :
-- 1) year function return always number then dont compare with char
-- 2) END_DATE>2015 are into 2 parts of your OR condition then you can factor it
-- 3) for better lisibility you can compare key in same line like it (X1, Y1)=(X2, Y2)
Select * from Table A
where END_DATE>2015 and (CODE = 'YYY' OR Part like 'Z%' AND plan like '5%')
AND EXISTS
(
SELECT * from table B
WHERE
(A.CUST_NUM, A.PArt, YEAR(A.Start_Date) - 1)=(B.CUST_NUM, B.Part, YEAR(B.Start_date))
)
--Other solution with join simple
Select distinct A.* from Table A
inner join Table B on (A.CUST_NUM, A.PArt, YEAR(A.Start_Date) - 1)=(B.CUST_NUM, B.Part, YEAR(B.Start_date))
where
A.END_DATE>2015 and (A.CODE = 'YYY' OR A.Part like 'Z%' AND A.plan like '5%')