0

如何在 MySQL 中进行以下查询?

Select SUM(T1.Amount) 
From 
( 
  Select  Distinct PersonName,Amount 
  From  tblusers as T1 
  where city ="xxx"
) 
4

3 回答 3

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

不过还是看你的实际需求。

于 2013-03-22T14:00:46.220 回答
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
于 2013-03-22T14:00:49.123 回答
0

我用下面的查询完成了它。但想知道是否有其他可能的方法来做到这一点。

    CREATE VIEW  T1 as (Select  Distinct PersonName,Amount From  tblusers  where city ="xxx" );

     Select SUM(Amount) From  T1
于 2013-03-22T14:05:04.683 回答