SQL查询-如何根据分组数字创建总和

时间:2018-09-18 22:24:12

标签: sql

我想知道每个等级(b.rankcode)收到了多少邮件(voicemailcount)。示例列“ b.rankcode”将具有x个具有等级编号的人,这些人在“ voicemailcount”中收到了邮件。如果可能的话,我只想查看语音邮件计数和等级代码列。

select 
    count(*) as [voicemailcount], a.linkedusermailboxname, b.RankCode as 'Rank'  
from  
    UMCallDataRecord a 
join 
    UMADUserAccounts b on a.LinkedUserMailboxName = b.EmailAddress
where   
    a.CallType = 'callansweringvoicemessage' 
    and month(a.[date]) = month(GetDate()) - 1   -- change this per month   -1 = lastmonth
group by 
    a.linkedusermailboxname, b.rankcode 
order by 
    b.rankcode

TIA!

2 个答案:

答案 0 :(得分:0)

我认为我们需要从Select和GroupBy中删除“ linkedusermailboxname”,并删除Join表及其“开...”。

SELECT 
       b.rankcode AS 'Rank'
       ,Count(*)   AS [voicemailcount]

FROM   umcalldatarecord a

WHERE  a.calltype = 'callansweringvoicemessage'
       AND Month(a.[date]) = Month(Getdate()) - 1
-- change this per month   -1 = lastmonth

GROUP  BY b.rankcode
ORDER  BY b.rankcode 

答案 1 :(得分:0)

似乎您只需要减少分组依据的列数

SELECT
    COUNT(*)   AS [voicemailcount]
  , ua.RankCode AS 'Rank'
FROM UMCallDataRecord AS cdr
JOIN UMADUserAccounts AS ua ON cdr.LinkedUserMailboxName = ua.EmailAddress
WHERE cdr.CallType = 'callansweringvoicemessage'
AND cdr.[date] >= dateadd(month, datediff(month,0, getDate())-1, 0) -- 1st day of last month
AND cdr.[date] < dateadd(month, datediff(month,0, getDate()), 0)    -- 1st day of current month
GROUP BY
    ua.rankcode
ORDER BY
    ua.rankcode

但是,我想提出一种不同的方法来定义日期范围,因为您可以在当前方法中包括任何年份的结果。上面的方法会将结果限制为上个月的所有结果,并且仅限于上个月。另请注意,我请勿使用between,这对日期范围而言并不理想。

我也同意“不良习惯:使用表别名(如(a,b,c)或(t1,t2,t3)”),使用有意义的别名,而不是基于“查询顺序”的别名。