如何在单个表mysql中比较和求和不同的列

时间:2015-02-26 08:49:08

标签: mysql join sum

I have a table with some duplicate stock ids and release date.The table table data is like below.

|STOCK_ID       |QTY| release_date|
-----------------------------------
|4046228009711    |12 | 25.02.2015  |
|4046228009711    |3  | 21.12.2014  |
|4046228009711    |13 | 21.12.2014  |
|4046228009711    |5  | 21.12.2014  |
------------------------------------

Now i want to sum the quantity of same stock id and same released_date and segregate records based on the released_date.
So the  out put should be like this.This is the expected output

|STOCK_ID       |QTY| release_date|
-----------------------------------
|4046228009711    |12 | 25.02.2015  |
|4046228009711    |21 | 21.12.2014  |
-----------------------------------

为了达到这个目的,我尝试了以下查询。     为此,我在临时表中插入了相同的数据。

SELECT t1.STOCK_ID,t1.`released_date
(SELECT SUM(Qty) FROM 
table1 t1 
WHERE h1.STOCK_ID = t2.STOCK_ID AND t1.released_date = t2.released_date
) AS 'Bestand'
FROM table1 t1
JOIN table2 t2  ON t1.STOCK_ID = t2.STOCK_ID 
GROUP BY t1.STOCK_ID

But i am getting the below output

|STOCK_ID       |QTY| release_date|
-----------------------------------
|4046228009711    |12 | 25.02.2015 |
-----------------------------------

任何人都可以帮助我在哪里犯错吗?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

这可以作为

完成
select 
STOCK_ID,
sum(QTY) as QTY,
release_date
from table_name
group by STOCK_ID,release_date