比较同一表中的数据

时间:2019-09-17 09:51:01

标签: sql sql-server left-join inner-join self-join

我有一个存储月度数据的表,我想比较一个时期内的数量移动。

这是表格的一个例子

a table with a client that can have one or more policies and each policy can have one or more funds. This is a one-to-many relationship

下面的SQL语句用于返回一段时间内发生的任何更改-任何基金/策略的部分或全部损失以及部分或全部收益。我已经与它抗争了一段时间-我们将不胜感激任何帮助。

我目前有5套工会-(其中政策和资金相符,所持数量有所不同,其中政策存在于先前而不是当前,反之亦然,证券存在于先前和之后。而不是当前的,反之亦然),但除了最后一对夫妇(其他证券存在于前一个而不是当前的证券,反之亦然)之外,其他工会也可以工作。它似乎并不会返回所有事件。

 SELECT distinct pc.[Client]
      ,pc.Policy
      ,cast(pc.Qty as decimal) AS CurrQ
      ,0 AS PrevQ
      ,cast(pc.Qty as decimal) - 0 AS QtyDiff
      ,CASE WHEN cast(pc.Qty as decimal) - 0 > 0 THEN 'Bought Units'
            WHEN cast(pc.Qty as decimal) - 0 < 0 THEN 'Sold Units'
          ELSE 'Unknown'
       END AS TransactionType
       ,convert(varchar,cast(pc.[ValDate] as date),103) AS CurrValDate
       ,'' AS PrevValDate
  FROM table pc
  WHERE convert(varchar,cast(pc.[ValDate] as date),103) = convert(varchar,getdate(),103)
  AND pc.Policy IN (SELECT policy
                    FROM table
                    WHERE convert(varchar(10),[ValDate],103) = convert(varchar(10),getdate()-1,103)

  AND pc.[Fund] NOT IN (SELECT PM.[Fund]
                        FROM table pc
                        LEFT JOIN table pm ON pc.policy = pm.policy
                        WHERE convert(varchar,cast(pc.[ValDate] as date),103) = convert(varchar,getdate(),103))
                        AND convert(varchar,cast(pm.[ValDate] as date),103) = convert(varchar,getdate()-1,103))

omits the fghij fund (that didn't exist previously on the same policy) and pqrst that existed but was fully sold - see the highlighted rows.)

1 个答案:

答案 0 :(得分:0)

正如@Larnu在注释部分正确提到的,查询中的额外条件将运行从“左联接”更改为“内联接”。我将代码更改为在ON子句中具有政策,资金和日期:

FROM table pc
LEFT JOIN table pm ON (pc.policy = pm.policy
                       AND pc.fund = pm.fund
                       AND pc.[ValDate]-1 = pm.[ValDate])

并摆脱了子查询。

再次感谢Larnu。