SQl将where子句应用于仅一个字段

时间:2014-05-26 22:04:45

标签: sql teradata

我想将WHERE子句应用于我的select查询的一个字段。互联网告诉我在我选择我的字段然后删除where子句的行中使用CASE WHEN。但后来我被告知我的" selected non aggregate values must be part of the associated group."

原始查询如下所示:

SELECT 
    CAST(EVENT_TIMESTAMP AS DATE) AS Date1, 
    COUNT(DISTINCT EMAIL) END AS Subs, 
    SUM(DWELL_MINUTES) AS Dwell
FROM VwNIMEventFct
INNER JOIN VwNIMUserDim ON VwNIMUserDim.NIM_USER_ID = VwNIMEventFct.NIM_USER_ID
INNER JOIN TmpNIMSalesForceDB ON VwNIMUserDim.USER_EMAIL_ADDRESS = EMAIL


WHERE Date1 >= '2013-11-01'
// The problem is here, in the AND clause
AND (SUBSCRIPTION_END_DATE > VwNIMEventFct.EVENT_TIMESTAMP OR SUBSCRIPTION_END_DATE 
IS NULL)

GROUP BY Date1
ORDER BY Date1

然后我在做了一些搜索之后更改了查询:

  SELECT 
    CAST(EVENT_TIMESTAMP AS DATE) AS Date1, 
    CASE WHEN (SUBSCRIPTION_END_DATE > Date1 OR SUBSCRIPTION_END_DATE IS NULL)
        THEN COUNT(DISTINCT TmpNIMSalesForceDB.EMAIL) END AS Subs, 
    SUM(VwNIMEventFct.DWELL_MINUTES) AS Dwell
    FROM RDMAVWSANDBOX.VwNIMEventFct
   INNER JOIN VwNIMUserDim ON VwNIMUserDim.NIM_USER_ID = VwNIMEventFct.NIM_USER_ID
   INNER JOIN TmpNIMSalesForceDB ON VwNIMUserDim.USER_EMAIL_ADDRESS = EMAIL
   WHERE Date1 >= '2013-11-01'
   GROUP BY Date1
   ORDER BY Date1

我想选择:  1)日期为"日期1"在查询中,然后,  2)对于每个日期,SUBSCRIPTION_END_DATE为NULL或将来(大于Date1)的不同电子邮件地址的计数,  3)一个字段的总和(我在这里很好)

我如何做2号?

根据答案编辑: 这部分select查询是否忽略,因此不计算空白记录 SUBSCRIPTION_END_DATE为空?

SELECT 
    COUNT(DISTINCT CASE  WHEN TmpNIMSalesForceDB.SUBSCRIPTION_END_DATE > Date1 OR TmpNIMSalesForceDB.SUBSCRIPTION_END_DATE IS NULL
             THEN TmpNIMSalesForceDB.EMAIL END) AS Subs, 

我需要计算SUBSCRIPTION_END_DATE为空/空的所有记录,或者那些日期在Date1之后的记录。

2 个答案:

答案 0 :(得分:2)

您需要将CASE语句放在COUNT中,而不是反之亦然,因为需要针对每一行(这行应该属于哪一行)进行评估,然后在每个组中进行聚合(该组中有多少行)落在非空组中。)

 COUNT(DISTINCT CASE WHEN (SUBSCRIPTION_END_DATE > Date1 OR SUBSCRIPTION_END_DATE IS NULL)
    THEN TmpNIMSalesForceDB.EMAIL END) AS Subs

COUNT将忽略CASE语句中缺少ELSE子句而隐式留下的NULL,因此只计算满足条件的行中不同的EMAIL值。

答案 1 :(得分:1)

case语句放在count函数内。

SELECT 
    CAST(EVENT_TIMESTAMP AS DATE) AS Date1, 
    COUNT(DISTINCT(CASE 
             WHEN SUBSCRIPTION_END_DATE > Date1 OR SUBSCRIPTION_END_DATE IS NULL
             THEN TmpNIMSalesForceDB.EMAIL END)) AS Subs, 
    SUM(VwNIMEventFct.DWELL_MINUTES) AS Dwell
FROM RDMAVWSANDBOX.VwNIMEventFct
    INNER JOIN VwNIMUserDim 
        ON VwNIMUserDim.NIM_USER_ID = VwNIMEventFct.NIM_USER_ID
    INNER JOIN TmpNIMSalesForceDB 
        ON VwNIMUserDim.USER_EMAIL_ADDRESS = EMAIL
WHERE Date1 >= '2013-11-01'
GROUP BY Date1
ORDER BY Date1