T-SQL基于列创建UID并对其进行迭代

时间:2016-09-14 16:20:21

标签: sql sql-server tsql sql-server-2014

我有以下代码来评估不同的时间段,并为每个组,

区分它们之间的差异

例如

TimePeriod  Value1
201607      50
201608      80

代码减去80-50 = 30(周期性)。

我还有一个基于我表中的几列创建的UID。我必须使用此自定义UID,并且无法在表格或任何特定列上使用PK。

WITH cte
AS (SELECT

  ISNULL(CAST(TransactionID AS nvarchar), '_nullTransactionId_') + ISNULL(Description, '_nullDescription_') + CAST(Account AS nvarchar) + Category + Currency + Entity + Scenario AS UID,

  LEFT(TimePeriod, 6) Period,
  SUM(Value1) Value1,
  CAST(LEFT(TimePeriod, 6) + '01' AS date) ord_date
FROM MyTestTable
GROUP BY LEFT(TimePeriod, 6),
         TransactionID,
         Description,
         Account,
         Category,
         Currency,
         Entity,
         Scenario,
         TimePeriod)
SELECT
  a.UID,
  a.Period,
  --a.Value1,
  ISNULL(a.Value1, 0) - ISNULL(b.Value1, 0) Periodic
FROM cte a
LEFT JOIN cte b
  ON a.ord_date = DATEADD(MONTH, 1, b.ord_date)
ORDER BY a.UID

问题是此代码生成的结果比我表中的行多得多。当我仔细观察它时,我可以看到任何给定UID的第一个(周期性)结果是正确的,但随后的结果是错误的。

我不知道从哪里开始寻求解决方案,我认为GROUP BY可能会导致这种情况发生,但我已经'列出分组中的字段,否则我无法生成UID。

非常感谢任何指导。

1 个答案:

答案 0 :(得分:1)

您可能希望对每个UID进行评估吗?在这种情况下,您缺少join子句中的UID。

查询应为:

WITH cte
AS (SELECT

  ISNULL(CAST(TransactionID AS nvarchar), '_nullTransactionId_') + ISNULL(Description, '_nullDescription_') + CAST(Account AS nvarchar) + Category + Currency + Entity + Scenario AS UID,

  LEFT(TimePeriod, 6) Period,
  SUM(Value1) Value1,
  CAST(LEFT(TimePeriod, 6) + '01' AS date) ord_date
FROM MyTestTable
GROUP BY LEFT(TimePeriod, 6),
         TransactionID,
         Description,
         Account,
         Category,
         Currency,
         Entity,
         Scenario,
         TimePeriod)
SELECT
  a.UID,
  a.Period,
  --a.Value1,
  ISNULL(a.Value1, 0) - ISNULL(b.Value1, 0) Periodic
FROM cte a
LEFT JOIN cte b
  ON a.UID = b.UID and a.ord_date = DATEADD(MONTH, 1, b.ord_date)
ORDER BY a.UID