我需要将VALUE_Expiration_DATE附加到DATE_EXPERATON 我的表有4个字段:
--- REFERENCE --- DATE (Production or EXPIRATION) --- COUNTRY --- VALUE ---
---- 1 ----------------------- 1014 (production) -------------------- CAN ---------- 105 -------
---- 1 ----------------------- 0215 (expiration) --------------------- CAN ---------- 203 -
............................................. ............................................................................
我的问题是如何在同一行获取2日期PROD和EXP的值,这对我来说不起作用:
SELECT
REFERENCE
,@PARAM_Production_DATE AS Production_DATE
,@PARAM_Expiration_DATE AS Expiration_DATE
,COUNTRY
,VALUE AS VALUE_Production_DATE
,**(
SELECT
value
FROM PRODUCT
WHERE REFERENCE <> 'XXX'
AND DATE in (@PARAM_Expiration_DATE)
) AS VALUE_Expiration_DATE**
FROM PRODUCT
WHERE REFERENCE <> 'XXX'
AND DATE in (@PARAM_Production_DATE)
以粗体显示的行不起作用,因为它返回的值超过1。 我该怎么办呢。
答案 0 :(得分:0)
您只是忘记了子查询中对主查询的引用(即确保访问相同的REFERENCE):
SELECT
REFERENCE
,@PARAM_Production_DATE AS Production_DATE
,@PARAM_Expiration_DATE AS Expiration_DATE
,COUNTRY
,VALUE AS VALUE_Production_DATE
,(
SELECT
value
FROM PRODUCT p2
WHERE p2.REFERENCE = p1.REFERENCE
AND DATE in (@PARAM_Expiration_DATE)
) AS VALUE_Expiration_DATE
FROM PRODUCT p1
WHERE REFERENCE <> 'XXX'
AND DATE in (@PARAM_Production_DATE);
您可以使用左连接执行相同的操作:
select
production.reference
,production.date as production_date
,@param_expiration_date as expiration_date
,production.country
,production.value as value_production_date
,expiration.value as value_expiration_date
from product production
left join product expiration
on expiration.reference = production.reference and expiration.date = @param_expiration_date
where production.date = @param_production_date
and production.reference <> 'XXX';