再来一个ChatGPT编程,这回是SQL。这个我都没写出来。大家看看问题的描述能看懂不?再看看ChatGPT给的代码对不对?
发表于 : 2023年 2月 11日 17:30
Given a SQL table "Account" with a unique increasing "AccountID" field and an integer field "AccountSize". Write a SQL to assign consecutive AccountIDs to a group with "GroupID" such that the sum of AccountSize in each group is just below a given threshold, say 1000.
代码: 全选
WITH cte AS (
SELECT
AccountID,
AccountSize,
SUM(AccountSize) OVER (ORDER BY AccountID) AS RunningTotal,
ROW_NUMBER() OVER (ORDER BY AccountID) AS RowNum
FROM Account
),
cte2 AS (
SELECT
AccountID,
AccountSize,
RunningTotal,
RowNum,
CASE
WHEN RunningTotal - AccountSize < 1000 THEN RowNum
ELSE RowNum - 1
END AS GroupID
FROM cte
)
SELECT
AccountID,
AccountSize,
GroupID
FROM cte2
ORDER BY AccountID;