我的查询运行正常:
select isnull(email,'') as Email ,isnull([ERPM First Name],'')+' '+isnull([ERPM Last Name],'')[User Name],
geo,CustomerID,BusinessID,courseid, MIN (CompletionDate) [1st Training Course],
CASE WHEN COURSEID IN (37445,37644,37443,37778,37435,37733,37584,37483,37392,37817,
37259,37597,37391,37393,37792,37816,37256,37257,37258,37484,37485,37486)
THEN 'Yes' ELSE 'No'
END AS [Is it a campaing course?],
CASE WHEN CompletionDate BETWEEN '2017-03-10' AND '2017-09-03' THEN 'Yes' ELSE 'No'
END AS [During Campaign],
CASE WHEN COURSEID IN (37256,37257,37258,37484,37485,37486) AND
CompletionDate BETWEEN '2017-03-10' AND '2017-09-03' THEN 'ON Period Bonus' ELSE '-'
END AS [1st BONUS]
from vw_Training_Cube
where [Is disti or subdisti?] = 'No' and [Is test account?] = 'No'
and Email<>'0'
GROUP BY isnull(email,''),isnull([ERPM First Name],'')+' '+isnull([ERPM Last Name],''),geo,CustomerID,BusinessID,courseid,
CASE WHEN COURSEID IN (37445,37644,37443,37778,37435,37733,37584,37483,37392,
37817,37259,37597,37391,37393,37792,37816,37256,37257,37258,37484,37485,37486)
THEN 'Yes' ELSE 'No'
END,
CASE WHEN CompletionDate BETWEEN '2017-03-10' AND '2017-09-03' THEN 'Yes' ELSE 'No'
END,
CASE WHEN COURSEID IN (37256,37257,37258,37484,37485,37486) AND
CompletionDate BETWEEN '2017-03-10' AND '2017-09-03' THEN 'ON Period Bonus' ELSE '-5'
END
但现在不是通过电子邮件进行分组,而是希望按业务ID进行分组。但简单地交换订单并不能解决问题。
答案 0 :(得分:0)
除非您需要COUNT()MIN()或MAX()等聚合函数,否则您可以使用select distinct
来简化查询。
SELECT DISTINCT
ISNULL(email, '')
AS Email
, ISNULL([ERPM First Name], '') + ' ' + ISNULL([ERPM Last Name], '')
[User Name]
, geo
, CustomerID
, BusinessID
, courseid
, MIN(CompletionDate) [1st Training Course]
, CASE
WHEN COURSEID IN (37445, 37644, 37443, 37778, 37435, 37733, 37584, 37483, 37392, 37817,
37259, 37597, 37391, 37393, 37792, 37816, 37256, 37257, 37258, 37484, 37485, 37486) THEN
'Yes'
ELSE
'No'
END AS [Is it a campaing course?]
, CASE
WHEN CompletionDate BETWEEN '2017-03-10' AND '2017-09-03' THEN
'Yes'
ELSE
'No'
END AS [During Campaign]
, CASE
WHEN COURSEID IN (37256, 37257, 37258, 37484, 37485, 37486) AND
CompletionDate BETWEEN '2017-03-10' AND '2017-09-03' THEN
'ON Period Bonus'
ELSE
'-'
END AS [1st BONUS]
FROM vw_Training_Cube
WHERE [Is disti or subdisti?] = 'No'
AND [Is test account?] = 'No'
AND Email <> '0'
ORDER BY BusinessID
要进一步减少行,还需要删除列 - 或 - 开始使用聚合函数。例如以下内容将生成最小的行集,以列出满足where条件的每个BusinessID。
SELECT DISTINCT
BusinessID
FROM vw_Training_Cube
WHERE [Is disti or subdisti?] = 'No'
AND [Is test account?] = 'No'
AND Email <> '0'
ORDER BY BusinessID
;
继续向其添加列以查看对行数的影响。