我在SQL服务器中创建了3个名为t_user_master,t_product_master和t_transaction的表.t_user_master通过列Users_id与t_transaction链接,而__product_master与t_transaction链接虽然列Products_id.Now我必须生成并输出包含的users_name(来自t_user_master),Product_name(来自t_product_master)与之链接,以便查看哪个用户订购了哪个产品。 这是我的代码片段 -
SELECT um.Users_Name,
pm.Product_Name,
(SELECT SUM(Transaction_Amount)
FROM t_transaction
WHERE Transaction_Type = 'Order'
GROUP BY Users_Id,
Product_Id) AS Ordered_quantity,
(SELECT SUM(Transaction_Amount)
FROM t_transaction
WHERE Transaction_Type = 'Payment'
GROUP BY Users_ID,
Product_Id) AS Amount_Paid,
(SELECT MAX(Transaction_Date)
FROM t_transaction
GROUP BY Users_Id,
Product_Id) AS Last_Transaction_Date,
(SELECT ( ( SUM(Transaction_Amount) * pm.Cost_per_Item ) - SUM(Transaction_Amount) ) )AS Balance
FROM t_user_master um
JOIN t_transaction tr
ON um.Users_ID = tr.Users_ID
JOIN t_product_master pm
ON tr.Product_ID = pm.Product_ID
GROUP BY um.Users_Name,pm.Product_Name
我已经记下了与语法相关的所有错误,但现在我面临另一个问题。执行后我收到此消息-Column't_product_master.Cost_Per_Item'在选择列表中无效,因为它不包含在聚合中函数或GROUP BY子句。 我哪里错了?
答案 0 :(得分:1)
你错过了第10行末尾的“)”和Last_Transaction_Date
之后的“,”。试试这个:
SELECT um.Users_Name,pm.Product_Name,
(SELECT SUM(Transaction_Amount)
FROM t_transaction
WHERE Transaction_Type='Order'
GROUP BY Users_Id,Product_Id
) AS Ordered_quantity,
(SELECT SUM(Transaction_Amount)
FROM t_transaction
WHERE Transaction_Type='Payment'
GROUP BY Users_ID,Product_Id
) AS Amount_Paid,
(SELECT MAX(Transaction_Date)
FROM t_transaction
GROUP BY Users_Id,Product_Id
) AS Last_Transaction_Date,
(SELECT ( ( SUM(Transaction_Amount)*pm.Cost_per_Item ) - SUM(Transaction_Amount) )
) AS Balance
FROM t_user_master um
JOIN t_transaction tr ON um.Users_ID=tr.Users_ID
JOIN t_product_master pm ON tr.Product_ID = pm.Product_ID
GROUP BY um.Users_Name,pm.Product_Name
答案 1 :(得分:0)
至少你错过了这一行末尾的“,”:
GROUP BY Users_Id,Product_Id) AS Last_Transaction_Date
答案 2 :(得分:0)
你在LastTransactionDate之后错过了一个逗号,而SELECT的最后一列看起来格格不入,即
(SELECT ((SUM(Transaction_Amount)*pm.Cost_per_Item)-SUM(Transaction_Amount)) AS Balance
答案 3 :(得分:0)
您的查询实际上有三个问题:
正确的查询是:
SELECT um.Users_Name,
pm.Product_Name,
(SELECT SUM(Transaction_Amount) FROM t_transaction
WHERE Transaction_Type='Order'
GROUP BY Users_Id,Product_Id) AS Ordered_quantity,
(SELECT SUM(Transaction_Amount) FROM t_transaction
WHERE Transaction_Type='Payment'
GROUP BY Users_ID,Product_Id )AS Amount_Paid,
(SELECT MAX(Transaction_Date) FROM t_transaction
GROUP BY Users_Id,Product_Id) AS Last_Transaction_Date, -- error 1
(SELECT ((SUM(Transaction_Amount)* sum(pm.Cost_per_Item))-SUM(Transaction_Amount))) AS
Balance -- error 2 and error 3
FROM t_user_master um
JOIN t_transaction tr ON um.Users_ID=tr.Users_ID
JOIN t_product_master pm ON tr.Product_ID = pm.Product_ID
GROUP BY um.Users_Name,pm.Product_Name ;
希望这有帮助!!!