我正在研究SQL Server 2014,我正在努力想出一个CASE语句逻辑,用一个" seq"将DisciplinaryActionReasonCode值改为记录。当permnum,DisciplinaryIncidentNumber和DateofDisciplinaryAction值重复时,数量为1。我在下面的SQL代码中所拥有的是我尝试过的内容。您会在我附上的图片中看到我需要根据我上面所述的内容将41值更改为21。
任何帮助/指示将不胜感激。谢谢。
这是我的SQL代码:
DECLARE @SchoolYear varchar(4) = '2016'
DECLARE @Submission int = 3;
SELECT @SchoolYear as SchoolYear,
@Submission AS Submission,
'220905' AS DistrictID,
Row_number() OVER (partition by A.incnum, A.locid ORDER BY A.dispnum DESC) as seq,
A.permnum,
B.txuniqueid,
'220905' + A.disschnum AS CampusIDofEnrollment,
stuff(A.incnum, 1, 0, replicate('0', 6 - len(A.incnum))) AS DisciplinaryIncidentNumber,
**CASE
WHEN ROW_NUMBER() OVER (PARTITION BY A.incnum, A.locid ORDER BY A.dispnum DESC) > 2
AND COUNT(A.PERMNUM) > 1
AND COUNT(STUFF(A.incnum, 1, 0, REPLICATE('0', 6 - LEN(A.incnum)))) > 1
AND COUNT(CONVERT(VARCHAR(10), A.dateofdisciplinaryaction, 120) > 1
THEN
--WHEN A.desccode LIKE 'XSTA-[0-9][0-9]%' THEN Substring(A.desccode, 6, 2) ELSE Substring(A.desccode, 1, 2)
END AS DisciplinaryActionReasonCode,**
CONVERT(VARCHAR(10), A.dateofdisciplinaryaction, 120) AS DateofDisciplinaryAction
FROM [dbo].[XXdiscipline] A
INNER JOIN [dbo].[XXstudents] B
ON A.permnum = B.permnum
WHERE (A.desccode LIKE '[0-9][0-9]%' OR A.desccode LIKE 'XSTA%')
AND (A.dispcode LIKE '[0-9][0-9]%' OR A.dispcode LIKE 'XSTA-[0-9][0-9]%')
AND A.PERMNUM = 1042003
ORDER BY permnum asc, DisciplinaryIncidentNumber asc, a.DISPNUM asc
答案 0 :(得分:0)
我认为您可以根据您在文本问题正文中所说的关于如何确定副本的内容来简化您的案例陈述:
CASE
WHEN ROW_NUMBER() OVER (PARTITION BY A.incnum, A.dateofdisciplinaryaction, A.permnum ORDER BY A.dispnum DESC) = 1
THEN 21
ELSE 41
END AS DisciplinaryActionReasonCode,
(如果你的21和41应该是相反的方式,将它们交换掉)
(实际上,你的规范没有多大意义,因为你已经向我们展示了一个主要是21的列,但是有一行是41,你说要将代码从41改为21,但这只是一个简单的21 as DisciplinaryReasonCode
)
答案 1 :(得分:0)
在另一个论坛中获得用户的帮助后,我发现CASE声明并非我所希望的解决方案。我创建了一个我的SQL代码的CTE语句,然后能够使用SQL Server内置的FIRST_VALUE函数查询正确的结果,这是SQL Server Central提供的Luis。这是最后的修复,希望它能帮助其他人:
SELECT SchoolYear, Submission, DistrictID, PERMNUM, DisciplinaryIncidentNumber, FIRST_VALUE(DisciplinaryActionReasonCode) OVER(PARTITION BY SchoolYear, Submission, DistrictID, PERMNUM ORDER BY seq) as DisciplinaryActionReasonCode
FROM CTE1
ORDER BY PERMNUM asc, DisciplinaryIncidentNumber asc, DisciplinaryActionReasonCode asc;