如何在MySQL中做以下查詢?如何從MySQL的視圖中選擇一個字段?
Select SUM(T1.Amount)
From
(
Select Distinct PersonName,Amount
From tblusers as T1
where city ="xxx"
)
如何在MySQL中做以下查詢?如何從MySQL的視圖中選擇一個字段?
Select SUM(T1.Amount)
From
(
Select Distinct PersonName,Amount
From tblusers as T1
where city ="xxx"
)
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
只是別名的子查詢:
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-22 14:10:14
@KESAVANPURUSOTHAMAN - np,很高興我們可以幫助! – sgeddes 2013-03-22 14:13:20
我做了下面的查詢。但想知道是否有任何其他可能的方式來做到這一點。
CREATE VIEW T1 as (Select Distinct PersonName,Amount From tblusers where city ="xxx");
Select SUM(Amount) From T1
它的工作。感謝兄弟。 – 2013-03-22 14:08:34
@KESAVANPURUSOTHAMAN歡迎您! – Taryn 2013-03-22 14:09:04