CREATE VIEW [dbo].[Payment_Transaction_vw]
AS
SELECT payment_trans_id,
Student_Info.student_fname,
Student_Info.student_lname,
Student_Info.ID_Number,
Trimester_Payment.deadline,
Transaction_Info.trans_name,
Payment_Transaction.amount,
Payment_Transaction.date_paid
FROM [Payment_Transaction]
INNER JOIN Student_Info
ON Payment_Transaction.student_info_id = Student_Info.student_info_id
INNER JOIN Trimester_Payment
ON Payment_Transaction.trimester_id = Trimester_Payment.trimester_id
INNER JOIN Transaction_Info
ON Payment_Transaction.trans_info_id = Transaction_Info.trans_info_id
GROUP BY ID_Number,trans_name;
这是我在Visual Studio的sql server中创建视图的脚本,我想将ID_Number& trans_name在表Payment_Transactions中具有重复值。我希望这个带有trans_name的ID_Number只显示一次。我还想总结每个具有相同trans_name的ID_number所支付的金额。
答案 0 :(得分:2)
您必须聚合不在group by
子句中的列。
例如,您想要返回date_paid
(payment_trans_id
= 1和2)中的哪一个? 2015年6月25日或2015年5月6日? SQL服务器不知道,所以你得到多行。
答案 1 :(得分:2)
使用group by
时,您需要确保聚合或合并任何唯一值,以便可以在一行中显示。就像现在一样,payment_trans_id
(和其他人)仍然是唯一的,因为你选择显示这些组是不可能完成的。
您想对payment_trans_id
,date_paid
,amount
...所有其他专栏做什么?
使用MAX()
,MIN()
和AVG()
的示例:
SELECT
MAX(payment_trans_id) AS payment_trans_id,
Transaction_Info.trans_name,
Student_Info.ID_Number,
AVG(Payment_Transaction.amount) AS amount,
MIN(Payment_Transaction.date_paid) AS date_paid
FROM [Payment_Transaction]
INNER JOIN Student_Info ON Payment_Transaction.student_info_id = Student_Info.student_info_id
INNER JOIN Trimester_Payment ON Payment_Transaction.trimester_id = Trimester_Payment.trimester_id
INNER JOIN Transaction_Info ON Payment_Transaction.trans_info_id = Transaction_Info.trans_info_id
GROUP BY ID_Number, trans_name;
对于EF的支持,也许这就足够了(也许不是):
SELECT
ISNULL(MAX(payment_trans_id),0) AS Id,
Transaction_Info.trans_name,
Student_Info.ID_Number,
AVG(Payment_Transaction.amount) AS amount,
MIN(Payment_Transaction.date_paid) AS date_paid
FROM [Payment_Transaction]
INNER JOIN Student_Info ON Payment_Transaction.student_info_id = Student_Info.student_info_id
INNER JOIN Trimester_Payment ON Payment_Transaction.trimester_id = Trimester_Payment.trimester_id
INNER JOIN Transaction_Info ON Payment_Transaction.trans_info_id = Transaction_Info.trans_info_id
GROUP BY ID_Number, trans_name;