如何在MySQL中执行以下查询?
Select SUM(T1.Amount)
From
(
Select Distinct PersonName,Amount
From tblusers as T1
where city ="xxx"
)
答案 0 :(得分:2)
只是别名子查询:
Select SUM(Amount)
From (
Select Distinct PersonName, Amount
From tblusers
where city ="xxx") t
如果您正在寻找每个人,请添加GROUP BY:
Select PersonName, SUM(Amount)
From (
Select Distinct PersonName, Amount
From tblusers
where city ="xxx") t
Group By PersonName
如果你真的想要每个人的总和(而不是不同人/数量的总和),那么你根本不需要子查询:
Select PersonName, SUM(Amount)
From tblusers
Where city ="xxx"
Group By PersonName
取决于您的实际需求。
答案 1 :(得分:1)
MySQL需要派生表或子查询的别名。所以你会想要使用以下内容:
Select SUM(t1.Amount)
From
(
Select Distinct PersonName, Amount
From tblusers
where city ="xxx"
) t1
根据您的需要,您应该可以使用以下内容:
select personName, sum(Amount)
from tblusers
where city = "xxx"
group by personName
或者,如果您只想归还总和,可以使用:
select sum(Amount)
from tblusers
where city = "xxx"
group by personName
答案 2 :(得分:0)
我是通过以下查询完成的。但是想知道还有其他可能的方法吗。
CREATE VIEW T1 as (Select Distinct PersonName,Amount From tblusers where city ="xxx" );
Select SUM(Amount) From T1