嵌套SQL选择

时间:2015-11-26 03:31:01

标签: sql

我有一个大的SQL表,我有以下查询返回一些基本信息:

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

结果

Customer Name         Total Emails
A                        1000
B                        9200
C                        11400

我要做的是获取在同一查询中返回的今天日期的电子邮件数量,例如:

结果

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

我可以修改原始查询以返回信息:

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

我需要的是基本上将这两个查询结合起来。

希望这是有道理的。

谢谢!

3 个答案:

答案 0 :(得分:2)

您可以使用条件聚合。像这样:

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;

答案 1 :(得分:0)

你也可以这样做。

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

答案 2 :(得分:0)

这应该有效

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