create table table1
(id int, sales int, Saledate date)
create table table2
(id int, sales int, invoicedate date)
insert into table1
values(1, 23, '2022-12-23'),
(2, 24, '2022-12-24'),
(3, 25, '2022-12-25')
insert into table2
values(1,0, '2022-12-25'),
(2, 0,'2022-12-26'),
(3, 0,'2022-12-27')
Select a.id,a.sales,
Case when A.Saledate=MAX(A.Saledate) Over() then A.Saledate else null End MaxSaledate,
Case when B.invoicedate=MAX(B.invoicedate) Over() then B.invoicedate else null End Maxinvoicedate
from table1 AS A
inner join table2 AS B
on A.id = B.id
drop table table1 ,table2
max invoice date and max sales amount
Hi Expert,
I am having below table and expected max invoice and sales date as output here is sql query
create table table1
(id int, sales int, Saledate date)
create table table2
(id int, sales int, invoicedate date)
insert into table1
values(1, 23, '2022-12-23'),
(2, 24, '2022-12-24'),
(3, 25, '2022-12-25')
insert into table2
values(1, '2022-12-25'),
(2, '2022-12-26'),
(3, '2022-12-27')
]1
Azure SQL Database
-
Jingyang Li 5,896 Reputation points Volunteer Moderator
2023-01-05T14:40:17.847+00:00
2 additional answers
Sort by: Most helpful
-
Subhrajyoti Ghosh 1 Reputation point
2023-01-05T13:49:34.47+00:00 @Shambhu Rai
You did not specify the foreign key to join these two tables. I am assuming the joining column is id. Hence the query should be as followsSelect MAX(A.Saledate), MAX(B.invoicedate)
from table1 AS A
inner join table2 AS B
on A.id = B.id -
Shambhu Rai 1,411 Reputation points
2023-01-05T14:08:07.057+00:00 tried to add all columns in table but unable to get right output
Select a.id,a.sales,MAX(A.Saledate), MAX(B.invoicedate)
from table1 AS A
inner join table2 AS B
on A.id = B.idgroup by a.id,a.sales