max invoice date and max sales amount

Shambhu Rai 1,411 Reputation points
2023-01-05T12:55:50.783+00:00

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')
![276440-image.png]1

Azure SQL Database
{count} votes

Accepted answer
  1. Jingyang Li 5,896 Reputation points Volunteer Moderator
    2023-01-05T14:40:17.847+00:00
    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  
    
    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. 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 follows

    Select MAX(A.Saledate), MAX(B.invoicedate)
    from table1 AS A
    inner join table2 AS B
    on A.id = B.id


  2. 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.id

    group by a.id,a.sales

    276526-image.png

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.