sql-server - 如果当前列在数据透视表中为空,则获取上一列值
问题描述
我有这样的数据:
Count | Status | Date
1 | S1 | Jan 2020
5 | S1 | Feb 2020
10 | S1 | Mar 2020
15 | S1 | Apr 2020
1 | S2 | Jan 2020
<- feb 2020 is missing for status2
10 | S2 | Mar 2020
<- apr 2020 is missing for status2
它基本上是每个月每个状态的累积数据,我需要将日期作为列名,然后按状态对它们进行分组,因此我需要对其进行透视。
当我旋转给定的数据时,它看起来像这样:
Status | Jan 2020 | Feb 2020 | Mar 2020 | Apr 2020
S1 | 1 | 5 | 10 | 15
S2 | 1 | NULL | 10 | NULL
所以我想要的是当该列为 NULL 时它将获取前一列的数据,因此在此示例中Feb 2020
,状态的数据S2
应该是1
因为它是具有值的前一列,也Apr 2020
应该是10
因为它是前一列具有值的列。
像这样的东西:
Status | Jan 2020 | Feb 2020 | Mar 2020 | Apr 2020
S1 | 1 | 5 | 10 | 15
S2 | 1 | 1 <- | 10 | 10 <-
当您像这样旋转数据时,如何实现这一目标?
这是我到目前为止的快速示例:
--Set the end of the month when getting the @columns variable
DECLARE @toDate DATETIME = DATEADD(MONTH, 1, GETDATE());
-- I have a function that gets the 1st month of the year until the month set by @toDate variable to set them as columns in the pivot so it would look like this:
DECLARE @columns NVARCHAR(MAX)= '[Jan 2020],[Feb 2020],[Mar 2020],[Apr 2020]';
SELECT * FROM
(
SELECT DISTINCT
FORMAT(Date, 'MMM yyyy') AS [Date],
SUM(COUNT(*)) OVER (PARTITION BY [Status] ORDER BY [Date]) AS [Count],
[Status]
FROM Table1
WHERE Date <= @toDate
GROUP BY [Date], FORMAT([Date], 'MMM yyyy'), [Status]
) t
PIVOT(
MAX(Count)
for [Date] IN (@columns)
) AS pivot_table;
解决方案
推荐阅读
- android - 当我尝试运行 gradle 时,Graphql 将错误返回为“无法解析 `Array` 值,预期的数组”
- couchbase - 使用 N1ql couchbase 查询的多对多关系
- asp.net - 通过对用户进行身份验证,使用 ASP.NET MVC App 访问 Azure 订阅信息
- android - RxJava:在不同的线程上运行 observable 并阻塞
- python - Python问题从用户那里获取输入N为每个偶数打印'EVEN'为每个奇数打印'ODD',从1到N
- c++ - 使用 node-addon-api 调用 Promise 会引发错误或不提供输出
- python - 如何使用 Python OpenCV 在 cv2.putText 中制作黑色背景
- git - 如何使用 git(及其速率限制)使许多服务器(5000+)保持最新?
- python - 我的 python 代码是如何越界的?
- android - 未显示 Android Studio 预览