gpt4 book ai didi

SQL查询过滤特定记录计数的记录

转载 作者:行者123 更新时间:2023-12-04 18:11:26 25 4
gpt4 key购买 nike

我有一个表,其中包含 Identity、RecordId、Type、Reading 和 IsDeleted 列。 Identity 是自动递增的主键,RecordId 是可以有重复值的整数,Type 是可以是“一”或“平均”的读数类型,读数是包含任何整数值的整数,IsDeleted 是位可以是 0 或 1,即假或真。
现在,我希望查询包含表的所有记录,如果每个 RecordId 的 COUNT(Id) 大于 2,则显示该 RecordId 的所有记录。

如果该特定 RecordId 的 COUNT(Id) == 2 并且两者的读数值,即“一个”或“平均”类型的记录相同,则仅显示平均记录。

如果 COUNT(Id) ==1 则仅显示该记录。

例如 :

Id          RecordId          Type          Reading       IsDeleted 
1 1 one 4 0
2 1 one 5 0
3 1 one 6 0
4 1 average 5 0
5 2 one 1 0
6 2 one 3 0
7 2 average 2 0
8 3 one 2 0
9 3 average 2 0
10 4 one 5 0
11 4 average 6 0
12 5 one 7 0

Ans结果可以是
Id          RecordId          Type          Reading       IsDeleted 
1 1 one 4 0
2 1 one 5 0
3 1 one 6 0
4 1 average 5 0
5 2 one 1 0
6 2 one 3 0
7 2 average 2 0
9 3 average 2 0
10 4 one 5 0
11 4 average 6 0
12 5 one 7 0

简而言之,我想跳过“一个”类型的读数,它的平均读数具有相同的值,并且“一个”类型读数的计数不超过一个。

最佳答案

看看这个程序

DECLARE @t TABLE(ID INT IDENTITY,RecordId INT,[Type] VARCHAR(10),Reading INT,IsDeleted BIT)
INSERT INTO @t VALUES
(1,'one',4,0),(1,'one',5,0),(1,'one',6,0),(1,'average',5,0),(2,'one',1,0),(2,'one',3,0),
(2,'average',2,0),(3,'one',2,0),(3,'average',2,0),(4,'one',5,0),(4,'average',6,0),(5,'one',7,0),
(6,'average',6,0),(6,'average',6,0),(7,'one',6,0),(7,'one',6,0)
--SELECT * FROM @t

;WITH GetAllRecordsCount AS
(
SELECT *,Cnt = COUNT(RecordId) OVER(PARTITION BY RecordId ORDER BY RecordId)
FROM @t
)
-- Condition 1 : When COUNT(RecordId) for each RecordId is greater than 2
-- then display all the records of that RecordId.
, GetRecordsWithCountMoreThan2 AS
(
SELECT * FROM GetAllRecordsCount WHERE Cnt > 2
)
-- Get all records where count = 2
, GetRecordsWithCountEquals2 AS
(
SELECT * FROM GetAllRecordsCount WHERE Cnt = 2
)
-- Condition 3 : When COUNT(RecordId) == 1 then display only that record.
, GetRecordsWithCountEquals1 AS
(
SELECT * FROM GetAllRecordsCount WHERE Cnt = 1
)

-- Condition 1: When COUNT(RecordId) > 2
SELECT * FROM GetRecordsWithCountMoreThan2 UNION ALL

-- Condition 2 : When COUNT(RecordId) == 2 for that specific RecordId and Reading value of
-- both i.e. 'one' or 'average' type of the records are same then display only
-- average record.
SELECT t1.* FROM GetRecordsWithCountEquals2 t1
JOIN (Select RecordId From GetRecordsWithCountEquals2 Where [Type] = ('one') )X
ON t1.RecordId = X.RecordId
AND t1.Type = 'average' UNION ALL

-- Condition 2: When COUNT(RecordId) = 1
SELECT * FROM GetRecordsWithCountEquals1

结果
ID  RecordId    Type    Reading IsDeleted   Cnt
1 1 one 4 0 4
2 1 one 5 0 4
3 1 one 6 0 4
4 1 average5 0 4
5 2 one 1 0 3
6 2 one 3 0 3
7 2 average2 0 3
9 3 average2 0 2
11 4 average6 0 2
12 5 one 7 0 1

关于SQL查询过滤特定记录计数的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12577319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com