[英]Select Record with Min value in a column and with specific value in another column
[英]How to count record by specific column in SQL SELECT statement and putting that value in another column of that row
我正在嘗試為同一學生的AppNum列中放入一個計數值,其中結果集中的FIRST / TOP記錄為1,隨后的記錄為2、3,依此類推。我嘗試使用GROUP BY而不是得到我想要的結果。 在下面的PIC中,第一個結果集顯示了我所得到的,第二個結果集是我所需要的。
這是我要做什么的圖片:
我嘗試獲取正確結果集的查詢如下。 任何幫助/方向將不勝感激:
SELECT
StudentID, Location, Status, EconomicDisadvantageCode,
StatusEffectiveDate, Enddate, SchoolYear, ApplicationTypeCode,
LastUpdated, UpdatedAppType, DataSource, COUNT(Status) AS AppNum
FROM
#MCS_5
WHERE
StudentID IN (SELECT StudentID
FROM #MCS_5
GROUP BY StudentID
HAVING COUNT(StudentID) > 1)
GROUP BY
Status, StudentID, Location, Status, EconomicDisadvantageCode,
StatusEffectiveDate, Enddate, SchoolYear, ApplicationTypeCode,
LastUpdated, UpdatedAppType, DataSource
ORDER BY
StudentID ASC, StatusEffectiveDate ASC;
使用row_number
函數,在這種情況下非常方便。
SELECT StudentID
,Location
,STATUS
,EconomicDisadvantageCode
,StatusEffectiveDate
,Enddate
,SchoolYear
,ApplicationTypeCode
,LastUpdated
,UpdatedAppType
,DataSource
,ROW_NUMBER () OVER (PARTITION BY Studentid,STATUS ORDER BY [STATUS])
Appnum
FROM #MCS_5
WHERE StudentID IN (
SELECT StudentID
FROM #MCS_5
GROUP BY StudentID
HAVING COUNT(StudentID) > 1
)
只需對所有功能使用窗口函數:
Select ...
From (select t.*,
Row_number() over (partition by studentid order by status) as seqnum,
Count(*) over (partition by studentid) as cnt
From #mcd_5 t
) t
Where cnt > 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.