我正在构建一个简单的记分牌。它基本上是公司中每个雇员引入外部用户(“推荐”)的总结清单。该列表只需通过对推荐的最后3个字母(=员工姓名首字母)进行分组来完成。但是,其中一名员工使用两种不同的推荐,我需要选择这两个推荐并将其总和为一个总和(因此我可以使用该值在我的记分板上排序)。
正常推荐看起来像这样:“%_ abc”。有问题的员工有两个推荐:“%_ xyz”和“RE%”。
这是当前的代码:
SELECT
RIGHT(Referral, 3) [Referral], COUNT(*) [Total]
FROM TableName
WHERE
CAST(Created AS DATE) = CAST(DATEADD(DAY, -1, GETDATE()) AS DATE)
AND
(
Referral LIKE '%_abc'
OR
Referral LIKE '%_xyz'
...
)
GROUP BY RIGHT(Referral, 3)
ORDER BY [Total] DESC
答案 0 :(得分:0)
我用以下代码解决了我的问题。欢迎任何优化提示。
SELECT Referral, SUM(Total) AS Total FROM
(
SELECT RIGHT(Referral, 3) [Referral], COUNT(*) [Total]
FROM TableName
WHERE
CAST(Created AS DATE) = CAST(GETDATE() AS DATE)
AND
(
Referral LIKE '%_abc'
OR
Referral LIKE '%_xyz'
...
)
GROUP BY RIGHT(Referral, 3)
UNION ALL
SELECT 'xyz' AS Referral, COUNT(*) [Total]
FROM TableName
WHERE
CAST(Created AS DATE) = CAST(GETDATE() AS DATE)
AND
LEFT(Referral, 2) = 'RE'
) t
GROUP BY t.Referral
ORDER BY Total DESC