我试图在PowerBI中创建一个图表,显示两个日期之间每个给定时间内数据库中问题的平均天数。
CREATE TABLE Issues
(IssueID int,IssueName varchar(10),created datetime, closed datetime);
INSERT INTO Issues
VALUES
(1,'a','2012-01-01 00:00:00', '2012-05-01 00:00:00'),
(2,'b','2012-03-01 00:00:00', '2012-06-01 00:00:00');
我的第一个查询显示了数据库中的所有数据:
SELECT IssueID,
DATEDIFF(DAY,created,ISNULL(closed,GETDATE())) AS 'Days_Open'
FROM Issues
结果:
IssueID Days_Open
1 4
2 3
我想找到的是每天,当天开放的问题和平均天数开放?
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2012-01-01'
SET @EndDate = '2012-07-01'
例: 问题每天开放
Date IssueID Days_Open
2012-01-01 1 0
2012-02-01 1 1
2012-03-01 1 2
2012-03-01 2 0
2012-04-01 1 3
2012-04-01 2 1
2012-05-01 1 4
2012-05-01 2 2
2012-06-01 2 3
Day 07 has no issues
平均
Date Average_Days_Open
2012-01-01 0 (1 issue just created)
2012-02-01 1 (1 issue - 1 day old)
2012-03-01 1 (2 issues - (2+0)/2 = 1)
2012-04-01 2 (2 issues - (3+1)/2 = 2)
2012-05-01 3 (2 issues - (4+2)/2 = 3)
2012-06-01 3 (1 issue - (0+3)/1 = 3)
2012-07-01 0 (Since there were no issues that day)
如果我可以从两者获取数据,那么我应该能够在PowerBi中创建类似于此的折线图: Chart
有人可以帮忙吗?
答案 0 :(得分:1)
基于语法我猜它是SQL Server:
1)查询:
WITH CTE_DatesTable
AS
(
SELECT CAST('20120101' as datetime) AS [date]
UNION ALL
SELECT DATEADD(dd, 1, [date])
FROM CTE_DatesTable
WHERE DATEADD(dd, 1, [date]) <= '20120106'
)
SELECT [date] , i.IssueId, DATEDIFF(DAY,i.created,d.[date]) AS Days_Open
FROM CTE_DatesTable d
JOIN Issues i
ON d.date BETWEEN i.created AND i.closed
ORDER BY [date], IssueId
OPTION (MAXRECURSION 0);
<强> DBFiddle Demo 强>
2)查询(平均):
WITH CTE_DatesTable
AS
(
SELECT CAST('20120101' as datetime) AS [date]
UNION ALL
SELECT DATEADD(dd, 1, [date])
FROM CTE_DatesTable
WHERE DATEADD(dd, 1, [date]) <= '20120106'
)
SELECT [date] ,AVG( DATEDIFF(DAY,i.created,d.[date]))
FROM CTE_DatesTable d
JOIN Issues i
ON d.date BETWEEN i.created AND i.closed
GROUP BY [date]
ORDER BY [date]
OPTION (MAXRECURSION 0);
<强> DBFiddle Demo2 强>
整个想法是生成日历表。
如果您需要超出范围的日期,可以使用LEFT JOIN
:
WITH CTE_DatesTable
AS
(
SELECT CAST('20120101' as datetime) AS [date]
UNION ALL
SELECT DATEADD(dd, 1, [date])
FROM CTE_DatesTable
WHERE DATEADD(dd, 1, [date]) <= '20120107'
)
SELECT [date] , COALESCE(AVG( DATEDIFF(DAY,i.created,d.[date])),0)
FROM CTE_DatesTable d
LEFT JOIN Issues i
ON d.date BETWEEN i.created AND i.closed
GROUP BY [date]
ORDER BY [date]
OPTION (MAXRECURSION 0);
<强> DBFiddle Demo3 强>