sqlcombiners

How to Combine 2 SQL queries into one


I have a table like below picture: enter image description here Query 1:

Select  MIN(SaleStartDate) as MinSaleDate 
from Sales 
where LessonID=1 and (DATEDIFF(day, CONVERT (char(10), GETDATE(), 126), Sales.SaleStartDate) > 0)

Result: 2017-02-10 (yyyy-MM-dd)

Query 2:

Select  MAX(SaleEndDate) as MaxSaleDate
from Sales 
where LessonID=1 and  (DATEDIFF(day, CONVERT (char(10), GETDATE(), 126), Sales.SaleEndDate) < 0)

Result: 2017-01-02 (yyyy-MM-dd)

I want to show 2 results with only 1 query. Please help me! Thank every body!


Solution

  • If you need both results in one row:

    Select  
    (
    Select  MIN(SaleStartDate) as MinSaleDate 
    from Sales 
    where LessonID=1 
    and (DATEDIFF(day, CONVERT (char(10), GETDATE(), 126), Sales.SaleStartDate) > 0)
    ),
    (
    Select  MAX(SaleEndDate) as MaxSaleDate
    from Sales 
    where LessonID=1 
    and  (DATEDIFF(day, CONVERT (char(10), GETDATE(), 126), Sales.SaleEndDate) < 0)
    )
    

    If you need the result in different rows use UNION:

    Select  
    (
    Select  MIN(SaleStartDate) as MinSaleDate 
    from Sales 
    where LessonID=1 
    and (DATEDIFF(day, CONVERT (char(10), GETDATE(), 126), Sales.SaleStartDate) > 0)
    ) UNION
    (
    Select  MAX(SaleEndDate) as MaxSaleDate
    from Sales 
    where LessonID=1 
    and  (DATEDIFF(day, CONVERT (char(10), GETDATE(), 126), Sales.SaleEndDate) < 0)
    )