使用EXISTS返回的值不正确

时间:2015-07-13 17:01:47

标签: sql sql-server tsql

我正在尝试使用子查询和fiscalyear运算符返回productid分组的最小EXISTS。无论出于何种原因,我从一组会计年度中获得任意值。子查询返回最小fiscalyear但外部查询不会为UPDATE选择它。有什么想法吗?

UPDATE#Temp
SET SALES_YEAR = sa.fiscalyear
FROM sales    sa
JOIN products p  ON p.id = sa.productid
JOIN #Temp    t  ON p.id = t.productid
WHERE exists ( select MIN(sa.fiscalyear),
                        sa.productid
               FROM sales    sa 
               JOIN products p  ON p.id = sa.productid
               JOIN #Temp    t  ON p.id = t.productid
               GROUP BY sa.productid
             )

3 个答案:

答案 0 :(得分:0)

尝试此查询

UPDATE  #Temp
SET     SALES_YEAR = A.fiscalyear
FROM  #Temp t 
JOIN (
    select  MIN(sa.fiscalyear),
            sa.productid
    FROM    sales sa
    JOIN    products p ON p.id = sa.productid
    JOIN    #Temp t ON p.id = t.productid
    GROUP BY sa.productid
) A ON T.PRODUCTID=A.PRODUCTID

答案 1 :(得分:0)

您不需要加入存在。另外,我假设你使用的是SQL Server。

实际上,我根本不认为你想要exists。只需像这样使用=

UPDATE t
   SET SALES_YEAR = sa.fiscalyear 
FROM #Temp t
WHERE t.product_id = (Select TOP 1 sa.productid
                      FROM sales sa JOIN
                           products p
                           ON p.id = sa.productid
                      ORDER BY sa.fiscalyear
                     )

答案 2 :(得分:0)

看起来你正在使用SQL Server。这应该是你:

UPDATE #Temp SET SALES_YEAR = x.fiscalyear
FROM #Temp t
join ( select product_id      = sa.productid ,
              fiscal_year = MIN( sa.fiscalyear )
       FROM sales    sa 
       JOIN products p  ON p.id = sa.productid
       JOIN #Temp    t  ON p.id = t.productid
       GROUP BY sa.productid
     ) x