I have two tables
t1
id Name Total
1 Alex 100
2 Bob 100
1 Alex 100
t2
id Amount
1 2
1 3
1 4
2 12
2 13
I need to get sum of Total and Amount.
**select Name, sum(Total) as Total, sum(Amount) as Amount,day
from t1,t2
Where t1.id=t2.id
group by Name**
Result:
Alex 600 18
Bob 200 25
Incorrect sum of Amount!
**select Name, sum(distinct Total) as Total, sum(Amount) as Amount,day
from t1,t2
Where t1.id=t2.id
group by Name**
Result:
Alex100 18
Bob 100 25
Incorrect sum of Amount.
MySql use distinct by value, i need distinct by id
corect result that need be is
Alex 200 18
Bob 100 25
How to get to this result?
select t1.Name,
sum(t1.Total) as Total,
sum(t2.Amount) as Amount,
day
from t1
left join
(
select id, sum(Amount) as Amount
from t2
group by id
) t2 on t1.id = t2.id
group by t1.Name
Related
I have two tables. One with amounts in quarterly increments, the other with amounts in annual increments. I want to join the two and sum FEES and COUNTS without double counting.
Table 1
CLM_NUM Year Quarter FEES
1234 2016 1 100
1234 2016 2 100
1234 2016 3 100
1234 2016 4 100
Table 2
CLM_NUM Year COUNT
1234 2016 10
Desired Result:
CLM_NUM Year FEES COUNT
1234 2016 400 10
However, my query causes the counts to be counted four times resulting in 40, not 10.
How do I resolve this?
SELECT Table1.CLM_NUM, Table1.YEAR, Sum(Table1.FEES) AS SumOfFEES,
Sum(Table2.COUNT) AS SumOfCOUNT
FROM Table1 INNER JOIN Table2 ON (Table1.CLM_NUM = Table2.CLM_NUM) AND (Table1.YEAR = Table2.YEAR)
GROUP BY Table1.CLM_NUM, Table1.YEAR;
You can use a sub-query. The SUM in the sub-query means it would work even if table 2 wasn't yearly (i.e. there were more rows per CLM_NUM/Year key).
SELECT
t1.clm_num,
t1.year,
sum(t1.fees),
(SELECT
sum(t2.count)
FROM
Table2 t2
WHERE t1.CLM_NUM = t2.CLM_NUM
AND t1.Year = t2.Year
GROUP BY
t2.CLM_NUM, t2.Year
) AS SumOfCount
FROM
Table1 t1
GROUP BY
t1.CLM_NUM, t1.Year
if access doesnt have max, use first
http://sqlfiddle.com/#!18/7ec1d/1
select t1.clm_num, t1.year,sum(t1.fees),max(t2.count)
from Table1 t1 inner join
Table2 t2 on t2.clm_num = t1.clm_num and (t1.YEAR = t2.YEAR)
GROUP BY t1.CLM_NUM, t1.YEAR
SELECT detailsID,`Topic 1 Scores`, MAX(Date) as "Date"
FROM Information.scores
WHERE `Topic 1 Scores` IS NOT NULL
GROUP BY `detailsID`,`Topic 1 Scores`
Is printing;
detailsID, Topic 1 Scores, MAX(Date)
2 0 26/09/2017
2 45 26/09/2017
2 100 26/09/2017
3 30 25/09/2017
3 80 14/10/2017
Rather than actually selecting the most recent date per detailsID which would be:
2 100 26/09/2017
3 80 14/10/2017
I want to retrieve TOPIC 1 SCORES with the most recent score (excluding null) (sorted by date) for each detailsID, (there are only detailsID 2 and 3 here, therefore only two results should return)
Solution 1 attempt
Inner subquery
You can do this:
SELECT t1.detailsID, t1.`Topic 1 Scores`, t1.date
FROM scores as t1
INNER JOIN
(
SELECT detailsID, MAX(date) as "LatestDate"
FROM scores
WHERE `Topic 1 Scores` IS NOT NULL
GROUP BY `detailsID`
) AS t2 ON t1.detailsID = t2.detailsID AND t1.date = t2.LatestDate
Demo
The subquery will give you the most recent date for each detailsID then in the outer query, there is a join with the original table to eliminate all the rows except those with the most recent date.
Update:
There are some rows with the same latest date, thats why you will have multiple rows with the same date and the same detailsID, to solve this you can add another aggregate for the score, so that you have only one row for each details id with the latest date and max score:
SELECT t1.detailsID, t1.`Topic 1 Scores`, t1.date
FROM scores as t1
INNER JOIN
(
SELECT detailsID, MAX(`Topic 1 Scores`) AS MaxScore, MAX(date) as "LatestDate"
FROM scores
WHERE `Topic 1 Scores` IS NOT NULL
GROUP BY `detailsID`
) AS t2 ON t1.detailsID = t2.detailsID
AND t1.date = t2.LatestDate
AND t1.`Topic 1 Scores` = t2.MaxScore
updated demo
Results:
| detailsID | Topic 1 Scores | date |
|-----------|----------------|------------|
| 2 | 100 | 2017-09-26 |
| 3 | 80 | 2017-10-14 |
WITH MYCTE AS
(
SELECT DetailsId, [Topic 1 Score], ROW_NUMBER() OVER ( Partition BY DetailsID ORDER BY DATE DESC) Num
FROM Scores
)
SELECT * FROM MYCTE WHERE num = 1
GO
I have a table of deposit/withdrawal transactions. I want to find the balance of each account as on a given date.
acctno date trantype amount balance seqno
12 1/2/14 dep 100 100 1
12 3/2/14 wdl 50 50 2
12 1/3/14 dep 200 250 3
13 2/2/14 dep 500 500 1
13 5/2/14 dep 100 600 2
13 5/4/14 dep 100 700 2
14 1/3/14 dep 200 200 1
Now I want to find the balance of each account as on 1/4/2014 and the reult should be something like this
acctno balance
12 250
13 600
14 200
Try this:
SELECT T1.Acctno, T1.Balance
FROM YourTable T1 INNER JOIN
(
SELECT T2.Acctno, T2.Date, MAX(T2.seqno) As MaxSeqno
FROM YourTable T2
GROUP BY T1.Acctno, T2.Date
)
ON(T1.Acctno = T2.Acctno AND T1.Date = T2.Date AND T1.seqno = MaxSeqno)
WHERE T1.Date = '2014-04-01'
try
select * from (select *,row_number() over
(partition by acctno order by date desc) as rno
from yourtable t WHERE T.Date <= '2014-04-01') t1 where rno=1
For Example, I have table like this:
Date | Id | Total
-----------------------
2014-01-08 1 15
2014-01-09 3 24
2014-02-04 3 24
2014-03-15 1 15
2015-01-03 1 20
2015-02-24 2 10
2015-03-02 2 16
2015-03-03 5 28
2015-03-09 5 28
I want the output to be:
Date | Id | Total
---------------------
2015-01-03 1 20
2014-02-04 3 24
2015-03-02 2 16
2015-03-09 5 28
Here the distinct values are Id. I need latest Total for each Id.
You can use left join as
select
t1.* from table_name t1
left join table_name t2
on t1.Id = t2.Id and t1.Date >t2.Date
where t2.Id is null
http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html
You can also use Max() in sql:
SELECT date, id, total
FROM table as a WHERE date = (SELECT MAX(date)
FROM table as b
WHERE a.id = b.id
)
You can do it as below
SELECT *
FROM YourTable D
WHERE date = (SELECT MAX(date) FROM YourTable WHERE ID = D.ID)
Another way is by using INNER JOIN
Find the latest date per ID then join result back to the table to get the value
select A.ID,A.Date,A.value
from yourtable A
INNER JOIN
(
select MAX(date) as Date,ID
from yourtable
group by ID
) B
ON A.ID =B.ID and A.Date = B.Date
The other answers didn't work for me. I found the following code, which worked great for me:
SELECT * FROM TABLE WHERE DATE IN (SELECT MAX(DATE) FROM TABLE)
I am using SSMS 2014, SQLServer
I have this working query
SELECT t1.id as stockid, t1.description as stockdescription, t2.inkoop as price , COUNT(t2.inkoop) as cnt,
(t2.inkoop * COUNT(t2.inkoop)) as totalamount
FROM database1.table_products t1
LEFT JOIN database1.table_stock t2 ON t1.id = t2.stock_id
WHERE 1
GROUP BY t2.inkoop
ORDER BY t1.id ASC
1 database, 2 tables:
t1 is the products 'description' database with ids and description
t2 is the stock, which has a lot of products for what price (purchased) and referenced by stock_id
Output:
id stockdescription price cnt totalamount
1 Product1 1067 15 16005
1 Product1 1290 103 132870
2 Product2 2750 70 192500
3 Product3 500 0 0
But now i have this 2nd database (database2) with a second inventory table (stock2) (exactly the same structure as database1.table_stock)
How do i alter my query so i can also add 'cnt2' and change total to my results?
Like this:
id stockdescription price cnt cnt2 totalcnt totalamount
1 Product1 1067 15 0 15 16005
1 Product1 1290 103 0 103 132870
2 Product2 2750 70 5 75 206250
3 Product3 500 0 4 4 2000
You can join multiple tables, but you'd get the full join of the two stock tables, which means you'd get wrong counts after the GROUP BY. You can avoid that by nesting your queries, e.g. along these lines:
SELECT sub.*, COUNT(stock2.inkoop) AS cnt2
FROM ( <paste your query here> ) AS sub
LEFT JOIN database2.stock2 AS stock2 ON sub.stockid = stock2.stock_id
GROUP BY sub.stockid
ORDER BY sub.stockid ASC
Now you have two left joins, each with its own GROUP BY. So each left join only sees a single left hand table factor, and you won't get duplicates caused by joining too many tables at once.