0

I have a single large SQL Table and I have the following query with returns some basic info:

SELECT 
     CustomerID AS "Customer Name" 
    ,COUNT(ID) AS "Total Emails"
FROM EmailDatas WHERE Expired = 0
GROUP BY CustomerID

Result

Customer Name         Total Emails
A                        1000
B                        9200
C                        11400

What I am trying to do is get a count of emails for todays date returned in the same query, something like:

Result

Customer Name         Total Emails          Emails Today
A                        1000                   34
B                        9200                   7
C                        11400                  54

I can amend the original query to return the info:

SELECT 
     CustomerID AS "Customer Name" 
    ,COUNT(ID) AS "Total Emails"
FROM EmailDatas WHERE Expired = 0 and starttime > getdate()
GROUP BY CustomerID

What I need is basically to have these 2 queries combined.

Hope this makes sense.

Thanks!

3
  • what is starttime here??? Commented Nov 26, 2015 at 3:35
  • Please tag your question with the database you are using. Commented Nov 26, 2015 at 3:36
  • Tag dbms used. (You are using product specific functionality.) Commented Nov 26, 2015 at 8:19

3 Answers 3

2

You can use conditional aggregation. Something like this:

SELECT CustomerID AS "Customer Name", 
       COUNT(ID) AS "Total Emails",
       SUM(CASE WHEN CAST(starttime as date) = CAST(getdate() as date) THEN 1 ELSE 0 END) as "Today's"
FROM EmailDatas
WHERE Expired = 0 
GROUP BY CustomerID;
Sign up to request clarification or add additional context in comments.

Comments

0

You can do something like this also.

select t1.CustomerName,t1.TotalEmails,
case when t2.EmailsToday is null then 0 
else t2.EmailsToday end as EmailsToday 
    from (SELECT 
         CustomerID AS CustomerName
        ,COUNT(ID) AS TotalEmails
        FROM EmailDatas WHERE Expired = 0
        GROUP BY CustomerID) t1 
    left join
        (SELECT 
         CustomerID AS CustomerName 
        ,COUNT(ID) AS EmailsToday
        FROM EmailDatas WHERE Expired = 0 and starttime > getdate()
        GROUP BY CustomerID) t2
    on t1.CustomerName=t2.CustomerName

Comments

0

This should work

SELECT
t1.CustomerID AS [Customer Name],
t1.[Total Emails],
t2.[Emails Today]
FROM
(SELECT 
CustomerID
,COUNT(ID) AS [Total Emails]
FROM EmailDatas WHERE Expired = 0
GROUP BY CustomerID) AS t1 LEFT OUTER JOIN
(SELECT 
CustomerID
,COUNT(ID) AS [Emails Today]
FROM EmailDatas WHERE Expired = 0 and starttime > getdate()
GROUP BY CustomerID) AS t2 
ON t1.CustomerID = t2.CustomerID

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.