tsql 不同的计数
我正在使用 SSMS 2008,并尝试选择参与两个不同事件的消费者数量。这可能是一个简单的查询,但它目前没有返回预期的计数。这是我的 T-SQL 代码,它更好地解释了我的尝试:
select [Program Quarter], event_name, consumer
from #consumer_initiations
where [Program Quarter] = 1 --and consumer = 'Byrd, Victoria Lynn'
group by [Program Quarter], event_name, consumer
having count (distinct event_name) > 1
所以上面的查询返回 0 条记录。如果我运行以下查询,我会获取所有记录:
select [Program Quarter], event_name, consumer
from #consumer_initiations
where [Program Quarter] = 1
这样我就可以看到其中一些记录的位置,其中存在同一季度、同一个人,但该人有 2 个或更多事件。现在,我如何计算同一个人参与 2 个或更多事件的次数?
I am using SSMS 2008 and am trying to select count of consumers who are part of two different events. Probably this is a simple query, but it is currently not returning expected count. Here is my T-SQL code which better explains what I tried:
select [Program Quarter], event_name, consumer
from #consumer_initiations
where [Program Quarter] = 1 --and consumer = 'Byrd, Victoria Lynn'
group by [Program Quarter], event_name, consumer
having count (distinct event_name) > 1
So this query above returns 0 records. if I run following query, I get all records:
select [Program Quarter], event_name, consumer
from #consumer_initiations
where [Program Quarter] = 1
So I can see where some of these records are where there is same quarter, same person, but 2 or more events for that person. Now, how can I count number of times that same person is part of 2 or more events?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
注意:快速思考,所以我确信这可以优化:
分解问题。
接下来,子查询类似于
完整查询类似于:
然后我会想到如何在没有子查询的情况下优化它。
NOTE: Quick off the top of my head, so I am sure this can be optimized:
Break the problem down.
Following this, the subquery is something like
And the full query something like:
I would then think of how to optimize this down without the subquery.
我已经使用您的结构创建了一些数据,这些数据将生成一些示例输出,如果您愿意,可以将其复制并粘贴到 SSMS 中。
结果
I've used your structure to create some data that will generate some example output, copy and paste into SSMS if you want to.
RESULTS