我有一个表,按日期值(ASC)排序。
+----+------------+-------+
| Id | Date | Value |
+----+------------+-------+
| 1 | 2018-01-01 | 10 |
| 2 | 2018-01-02 | 5 |
| 3 | 2018-01-03 | 15 |
| 4 | 2018-01-04 | 0 |
| 5 | 2018-01-05 | 5 |
| 6 | 2018-01-06 | 10 |
| 7 | 2018-01-07 | 5 |
| 8 | 2018-01-08 | 0 |
| 9 | 2018-01-09 | 0 |
| 10 | 2018-01-10 | 10 |
+----+------------+-------+
我想创建一个视图,该视图仅在值的和大于30时才返回记录,从第一条记录开始。所以我的阈值是30,所有值在前30的记录都应该被隐藏。达到此阈值后的所有记录都需要显示。
这意味着我需要的结果如下所示:
+----+------------+-------+
| Id | Date | Value |
+----+------------+-------+
| 4 | 2018-01-04 | 0 |
| 5 | 2018-01-05 | 5 |
| 6 | 2018-01-06 | 10 |
| 7 | 2018-01-07 | 5 |
| 8 | 2018-01-08 | 0 |
| 9 | 2018-01-09 | 0 |
| 10 | 2018-01-10 | 10 |
+----+------------+-------+
如您所见,Id的1、2和3被省略了,因为它们的值(10、5和15)总和为30。达到此阈值后,剩余的记录将可见(甚至Id为4的0值也可见)。
我已经创建了一些脚本来设置包含数据的测试表:
-- Create test table
CREATE TABLE thresholdTest (
[Id] INT IDENTITY(1,1) PRIMARY KEY,
[Date] DATE NOT NULL,
[Value] INT NOT NULL
)
-- Insert dummies
INSERT INTO [thresholdTest] ([Date],[Value])
VALUES
('2018-01-01',10),
('2018-01-02',5),
('2018-01-03',15),
('2018-01-04',0),
('2018-01-05',5),
('2018-01-06',10),
('2018-01-07',5),
('2018-01-08',0),
('2018-01-09',0),
('2018-01-10',10);
-- Select ordered by date
SELECT *
FROM [thresholdTest]
ORDER BY [Date] ASC
我所需要的只是一个SELECT语句/视图。阈值始终是静态的(本例中为30)。当然,数据可以不同,但它始终是按日期排序的,并且包含一个值。
提前谢谢你。
发布于 2018-08-01 05:17:48
我会使用一个窗口函数:
;with cte as(
select *, tot = sum([Value]) over (order by [Date])
from thresholdTest
)
select
Id,
[Date],
[Value]
from cte
where
(tot >= 30 and [Value] = 0)
or tot > 30
发布于 2018-08-01 05:22:36
还有另一种方法
select t1.id, t1.Date,t1.Value
from [thresholdTest] t1
inner join [thresholdTest] t2 on t1.id >= t2.id
group by t1.id, t1.value, t1.Date
HAVING SUM(t2.VAlue)>30 OR( SUM(t2.value)=30 AND t1.value=0)
https://stackoverflow.com/questions/51622039
复制相似问题