如何在sql语句中使用`OR`条件?

时间:2013-03-29 06:36:06

标签: sql sql-server sql-server-2008 tsql

我想在下面的sql语句中使用'OR'条件请帮我这样做。

   SELECT DATE, SecurityId
    FROM StateStreet
    INNER JOIN Securities ON StateStreet.SecurityID = Securities.securityid
    AND (     (SecurityName LIKE '% R V %'
               AND Quantity < 0
               AND PortfolioId =@portfolioID)
           OR (SecurityName NOT LIKE '% R V %'
               AND Quantity > 0
               AND PortfolioId=@PortfolioID)
           OR (Value = Quantity
               AND Securities.PortfolioId =@PortfolioID) 
         )
   WHERE CONVERT(DATETIME,PeriodEndDate) = @PositionDate 

请帮我在上述声明中使用OR条件,我需要在OR条件下检查3个语句。

2 个答案:

答案 0 :(得分:2)

您好像忘了WHERE子句:

SELECT 
    DATE,
    SecurityId              
FROM
    StateStreet 
INNER JOIN
    Securities ON StateStreet.SecurityID =  Securities.securityid 
WHERE
    (SecurityName LIKE '% R V %' AND Quantity < 0  AND PortfolioId = @portfolioID)
OR
    (SecurityName NOT LIKE '% R V %' AND Quantity > 0  AND PortfolioId = @PortfolioID)
OR
    (Value = Quantity AND Securities.PortfolioId = @PortfolioID)

答案 1 :(得分:0)

这是您第二次发布相同的问题。

您正在使用OR条件。

要么您不理解优先级,搜索条件,要么数据不是您所假设的。

订单是:
按位(你没有任何这些)
()


或者

打破查询。

SELECT DATE, SecurityId, SecurityName, Quantity, Value, PortfolioId
FROM StateStreet
INNER JOIN Securities 
   ON StateStreet.SecurityID = Securities.securityid
WHERE CONVERT(DATETIME,PeriodEndDate) = @PositionDate 

然后
您可以将AND PortfolioId = @ portfolioID拉出来,因为它在每个或作为和

SELECT DATE, SecurityId, SecurityName, Quantity, Value, PortfolioId
FROM StateStreet
INNER JOIN Securities 
   ON StateStreet.SecurityID = Securities.securityid 
  AND PortfolioId = @portfolioID
WHERE CONVERT(DATETIME,PeriodEndDate) = @PositionDate 

SELECT DATE, SecurityId, SecurityName, Quantity, Value, PortfolioId
FROM StateStreet
INNER JOIN Securities 
   ON StateStreet.SecurityID = Securities.securityid 
  AND PortfolioId = @portfolioID
  AND (      Value = Quantity
        OR ( SecurityName LIKE '% R V %' )
      )
WHERE CONVERT(DATETIME,PeriodEndDate) = @PositionDate