Dear,
I am working in the construction of a stored procedure, I need to obtain a date field from a Table B depending on a particular state, by means of a subquery in a table A, I explain:
Table A contains a product and table B stores the historical movements of some record of table A, by means of a query I need to bring the data from table A and a date of a specific movement from table B.
Table A = lead
Table B = lead_history
Query (Contains a where for an id to work only for 1 case, the state to look for in table B, is 14):
select l.*
,(SELECT lh.execution_date FROM lead_history lh join lead l ON lh.lead_id = l.id WHERE lh.lead_state_id=l.lead_state_id ) AS FechaPropuestaGanada
from lead l where (l.lead_state_id=14) and l.id=22142
Result of the executed query:
Msg 512, Level 16, State 1, Line 4
La subconsulta ha devuelto más de un valor, lo que no es correcto cuando va a continuación de =, !=, <, <=, >, >= o cuando se utiliza como expresión.
Note: Table B stores all state changes for each Product in table A, but no state is repeated (ex: there are no 2 records in the "Won" status for a product in table A, only 1)
If I separate the subquery by an ID from table A in specific, it would be like this:
SELECT lh.execution_date FROM lead_history lh join lead l ON lh.lead_id = l.id WHERE lh.lead_state_id=14 and lh.lead_id = 22142
and my result is this:
2017-06-21 11:41:22.303
That's what I need, but I can not add it to the main query (this result is saved in an additional field of the main Query, with the alias'GuidedPropDate ')