Search code examples
sqlsql-serverperformancedatabase-performanceprocessing-efficiency

SQL: Is it possible to merge these two SQL statements into a single query?


I am using MS SQL Server 2014 on Windows 7.

In the database I have a table named Orders, which looks like this:

OrderID | CustomerID | OrderDate | ...   
----------------------------------------
1028      90           2015-10-10   
...
2416      68           2016-02-12

I needed two things:

  1. the total number of customers
  2. the number of customers this year.

I am a beginner in SQL, but I managed to write 2 SQL statements in my app that seem to do the job:

For requirement #1

SELECT COUNT(DISTINCT CustomerID) FROM Orders; // result = 74   

For requirement #2:

SELECT COUNT(DISTINCT CustomerID) FROM Orders WHERE OrderDate >= '2016-01-01'; // result = 34   

I would like to know if it's possible to merge/combine somehow the above 2 SQL statements into one single query...? Of course, I need both results: the total customers (74 in above case) and also the customers of this year (i.e. 34).

The database is a remote database, so any idea to speed-up the query performance is highly welcome :)


Solution

  • Use conditional aggregation:

    SELECT COUNT(DISTINCT CustomerID) as Total,
           COUNT(DISTINCT CASE WHEN OrderDate >= '2016-01-01' THEN CustomerID END) as Total_2016
    FROM Orders;