这是我的表:
+-----+-----+-------------+-------------+-----+
| ID | tFK | schedDate | complDate | res |
+=====+=====+=============+=============+=====+
| 1 | 2 | 2018-02-01 | 2018-02-01 | 2 |
+-----+-----+-------------+-------------+-----+
| 2 | 2 | 2018-02-02 | 2018-02-02 | 2 |
+-----+-----+-------------+-------------+-----+
| 3 | 2 | 2018-02-03 | 2018-02-03 | 2 |
+-----+-----+-------------+-------------+-----+
| 4 | 2 | 2018-02-04 | 2018-02-04 | 3 |
+-----+-----+-------------+-------------+-----+
| 5 | 2 | 2018-02-05 | 2018-02-05 | 2 |
+-----+-----+-------------+-------------+-----+
| 6 | 2 | 2018-02-06 | 2018-02-06 | 2 |
+-----+-----+-------------+-------------+-----+
我想只计算输入的tFK是否与之前相同的tFK输入的结果相同,无论日期是什么,这是我到目前为止的语法,但它不是我想要的输出。 如何添加' CONSECUTIVE'我的查询的标准?
SELECT [taskFK],COUNT([result]) resultCount
FROM [cil].[cil].[schedule]
where scheduledDate between '2018-01-01' AND '2018-02-22'
AND completionDate IS NOT NULL
AND result=2
GROUP BY taskFK
HAVING COUNT([result]) > @variable
ORDER BY taskFK
编辑:
这将是预期的输出: 如果@variable设置为2,则输出将为tFK = 2 如果@variable设置为3,则输出将为tFK = 1
由于
答案 0 :(得分:1)
您可以使用LAG功能确定您的资源与该tfk的前一资产相同。由于我们不能在聚合函数中使用窗口函数,我们将使表变量或CTE计数并计算与之前的tfk结果匹配的记录。
DECLARE @schedule table (
id INT,
tfk INT,
scheddate DATE,
compldate DATE,
res INT
)
INSERT INTO @schedule VALUES
(1,2,'2018-02-01','2018-02-01',2),
(2,2,'2018-02-02','2018-02-02',2),
(3,2,'2018-02-03','2018-02-03',2),
(4,2,'2018-02-04','2018-02-04',3),
(5,2,'2018-02-05','2018-02-05',2),
(6,2,'2018-02-06','2018-02-06',2)
SELECT
tfk,
SUM(same_as_prev) AS sum_res
FROM (
SELECT
id,
tfk,
scheddate,
compldate,
res,
CASE WHEN LAG(res) OVER (PARTITION BY tfk ORDER BY ID) = res THEN 1 ELSE 0 END AS same_as_prev
FROM @schedule
) tbl
WHERE scheddate between '2018-01-01' AND '2018-02-22'
AND compldate IS NOT NULL
AND res = 2
GROUP BY tfk
HAVING SUM(same_as_prev) > 2
ORDER BY tfk
答案 1 :(得分:0)
我假设您可以执行类似这样的操作来计算是否已存在行。
SELECT
DISTINCT Count(tFK) AS [Count], tFK
FROM schedule
Where res=3
GROUP BY tFK
HAVING Count(tFK)>0