Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Here is the following query

select CAST(DepositeDate AS DATE) as DepositeDate,SUM(TotalAmount) as Amount
from Payment
group by DepositeDate 

I am getting the following result.

DepositeDate | Amount | 
2021-04-30   | 50     | 
2021-04-30   | 50     | 
2021-04-26   | 75     | 
2021-04-11   | 30     | 
2021-04-11   | 30     | 

But I need the following result

DepositeDate | Amount | 
2021-04-30   | 100    | 
2021-04-26   | 75     | 
2021-04-11   | 60     |  

Is this possible without using CTE?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
149 views
Welcome To Ask or Share your Answers For Others

1 Answer

Apparently, your DepositeDate column has a time component. Repeat the expression in the GROUP BY:

select CAST(DepositeDate AS DATE) as DepositeDate,
       SUM(TotalAmount) as Amount
from Payment
group by CAST(DepositeDate AS DATE) 
order by CAST(DepositeDate AS DATE);

SQL Server does not recognize aliases in the GROUP BY. So DepositeDate is always going to refer to a column defined in the FROM clause and not the expression in the select.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...