0

これは学生図書館のプロジェクトの一部です。

と の 2 つのテーブルがありalertsますborrows

borrowsstudentIDbookIDおよびが含まれますdate of borrowing

alertsは、どの生徒が何冊の本を延滞しているかを示します。

このコードは、延滞している生徒ごとに行を挿入し、延滞している本の数を数えることになっています。

Est_Return_Date = return_date + 30

insert into dbo.Alert (studentID, AlertCount)
    values ((select distinct (studentID )from dbo.Borrows
        where Est_Return_Date < GETDATE()
        and return_date is null),
        (select count( studentID) from dbo.Borrows
        where Est_Return_Date < GETDATE()
        and return_date is null ))
4

2 に答える 2

2

サブクエリの代わりに使用するGROUP BY必要があります。必要なのは、studentId ごとの結果でGROUP BYありCOUNT、アラートのある行です。

INSERT INTO dbo.Alert (studentID, AlertCount)
SELECT studentID,COUNT(*)
FROM dbo.Borrows
WHERE Est_Return_Date < GETDATE()
AND return_date is NULL
GROUP BY studentID;

ここでデモ。

于 2012-08-25T14:14:08.077 に答える
1

これを試して

 insert into dbo.Alert (studentID, AlertCount)
select studentId, count(*) as AlertCount from dbo.Borrows  where Est_Return_Date < GETDATE()
        and return_date is null group by studentId

何をしたいのかを考えると、クエリは常に1つの値を挿入します-カウントは生徒の総数を返し、おそらく別の選択も1つの値のみを返します。このクエリは、学生ごとにグループ化され、期限切れになると、他のテーブルの合計本数をカウントします。

ここでgroupについて何かを読んでください。MySQLの場合も機能します。一例を挙げた別のページがここにあります

于 2012-08-25T14:06:13.837 に答える