在 SQL 中使用 count 函数的问题
我正在运行此查询来获取用户预订的带保险的销售总数和不带保险的销售总数。然而,由于某种原因,所有用户都获得相同的计数。我如何更改查询以显示每个用户的总计。
我想要的基本上是计算出每个用户有多少次预订(有或没有保险销售)
Bookingby 是代理
,T0 是包含有关不包含保险的预订信息的表
,t1 是表包含有关保险预订的信息
,而两个表都提供相同的信息,我如何从两个表中获取每个代理的预订总数
SELECT t0.BookedBy, count(t0.resnumber) as NonInsurance, COUNT(t1.resnumber) as Insurance
FROM (SELECT BookedBy, ResNumber, DATEPART(year, BookDate) AS Year, DATEPART(month, BookDate) AS month
FROM dbo.ResGeneral
WHERE ResNumber NOT IN (SELECT ResNumber FROM dbo.ResItinerary_insurance)
and ResStatus = 'a'
GROUP BY BookedBy, ResNumber, BookDate) t0
left JOIN (SELECT BookedBy, ResNumber, DATEPART(year, BookDate) AS Year, DATEPART(month, BookDate) AS month
FROM dbo.ResGeneral
WHERE ResNumber IN (SELECT ResNumber FROM dbo.ResItinerary_insurance)
and ResStatus = 'a') t1
ON t1.year = t0.year
group by t0.bookedby
I am running this query to get a count of the bookedby users total number of sales with insurance and total number of sales without insurance. However, all of the users are getting the same count for some reason. how can i change my query to show each users totals instead.
what i want is basically to figure out how many bookings each user had with and without insurance sales
bookedby is the agent
and T0 is the table that includes the information about bookings that do not include insurance
and t1 is the table that includes information about bookings with insurance
while both tables provide the same information how can i get a total by booked by for each agent from both tables
SELECT t0.BookedBy, count(t0.resnumber) as NonInsurance, COUNT(t1.resnumber) as Insurance
FROM (SELECT BookedBy, ResNumber, DATEPART(year, BookDate) AS Year, DATEPART(month, BookDate) AS month
FROM dbo.ResGeneral
WHERE ResNumber NOT IN (SELECT ResNumber FROM dbo.ResItinerary_insurance)
and ResStatus = 'a'
GROUP BY BookedBy, ResNumber, BookDate) t0
left JOIN (SELECT BookedBy, ResNumber, DATEPART(year, BookDate) AS Year, DATEPART(month, BookDate) AS month
FROM dbo.ResGeneral
WHERE ResNumber IN (SELECT ResNumber FROM dbo.ResItinerary_insurance)
and ResStatus = 'a') t1
ON t1.year = t0.year
group by t0.bookedby
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这个查询是等效的:
I think this query is equivalent:
您的连接条件看起来不正确:
这将交叉连接具有同一年份的所有行。您可能想要使用更具体的条件,例如
t1.BookedBy = t0.BookedBy
。Your join condition looks incorrect:
This will cross join all rows with the same year. You probably want to use a more specific condition, for example
t1.BookedBy = t0.BookedBy
.