【问题标题】:Get a new column with updated values, where each row change in time depending on the actual column?获取具有更新值的新列,其中每一行根据实际列及时更改?
【发布时间】:2025-12-03 17:05:01
【问题描述】:

我有一些数据,其中包括以数字表示的 ID、日期和地点作为列。我需要模拟实时更新,在其中创建一个新列,说明目前有多少个不同的地方,所以每次新的地方出现在列中时,新列都会改变它的值并显示它。

这只是具有数亿行的原始表的一小部分。

这是一个例子,左表是原始表,右表是我需要的。

我试图用这段代码来做,但我不能将函数 DISTINCT 与OVER 子句一起使用。

    SELECT ID, Dates, Place,
    count (distinct(Place)) OVER (PARTITION BY Place ORDER BY Dates) AS 
    DiffPlaces
    FROM #informacion_prendaria_muestra
    order by ID;

【问题讨论】:

  • 请不要使用图片或图片链接。而是将数据添加为文本。
  • 仅供参考,编辑器有一个代码格式按钮。

标签: sql sql-server


【解决方案1】:

我认为在 SQL server 中使用DENSE_RANK() 是可能的

你可以试试这个

SELECT ID, Dates, Place,
DENSE_RANK() OVER(ORDER BY Place) AS 
DiffPlaces
FROM #informacion_prendaria_muestra

【讨论】:

    【解决方案2】:

    我认为您可以使用这样的自联接查询 - 无需使用 Windows 函数 -:

    select 
        t.ID, t.[Date], t.Place, 
        count(distinct tt.Place) diffPlace
    from 
        yourTable t left join 
        yourTable tt on t.ID = tt.ID and t.[Date] >= tt.[Date]
    group by 
        t.ID, t.[Date], t.Place
    order by 
        Id, [Date];
    

    SQL Fiddle Demo

    【讨论】: