[英]How to count distinct results from a already executed SQL Query?
select application from l3_usage
where function in ('dbms', 'web', 'app')
group by application, function
order by application
This is the result image when I execute the above query. 这是我执行上述查询时的结果图像。
I want to now count the number of times applications occur. 我现在想计算应用程序发生的次数。 So for example: Budget : 3 CSR : 3 FMS : 3 Facilities : 1 Inventory : 3 因此,例如:预算:3 CSR:3 FMS:3设施:1库存:3
etc... 等等...
I have tried 我努力了
select application, count(application) from l3_usage
where function in ('dbms', 'web', 'app')
group by application
order by application
but I get random count numbers that do not relate to the count I was looking for. 但我得到的随机计数数字与我要查找的计数无关。
Could anyone help? 有人可以帮忙吗? Thanks! 谢谢!
EDIT ::::: 编辑:::::
my ultimate purpose of doing this is to get only applications that have count values less than 3. 我这样做的最终目的是仅获得计数值小于3的应用程序。
Which in this case, should return just "Facilities" and "SCM". 在这种情况下,应该只返回“设施”和“ SCM”。
Try this query: 试试这个查询:
SELECT x.application, COUNT(*) As Frequency
FROM
(
SELECT application
FROM l3_usage
WHERE function IN ('dbms', 'web', 'app')
GROUP BY application, function
ORDER BY application
) AS x
GROUP BY x.application
HAVING COUNT(*) < 3
ORDER BY COUNT(*)
I query the result set you posted in your answer and obtain the COUNT
for each group. 我查询您在答案中发布的结果集,并获取每个组的COUNT
。 Notice that this COUNT
is the number of unique function
values for each application
group. 请注意,此COUNT
是每个application
组的唯一function
值的数量。 You should get this result: 您应该得到以下结果:
+-------------+-----------+
| application | Frequency |
+-------------+-----------+
| Facilities | 1 |
| SCM | 1 |
+-------------+-----------+
Update: 更新:
A much easier way to do your query is: 一种更简单的查询方法是:
SELECT application, COUNT(DISTINCT function) As Frequency
FROM l3_usage
WHERE function IN ('dbms', 'web', 'app')
GROUP BY application
HAVING COUNT(DISTINCT function) < 3
ORDER BY application
You had the right idea in the beginning, but you needed to SELECT
the number of distinct function
s for each application group. 一开始您的想法是正确的,但是您需要为每个应用程序组SELECT
不同function
的数量。
I have used subqueries which I had concatenated count to your query. 我使用了已连接到您的查询中的子查询。 If you want distinct row count use distinct
in-front of count(*)
in @count query 如果您想要不同的行计数,请在@count查询中使用count(*)
distinct
前端
declare @count nvarchar(max)= (select count(*)
from l3_usage
where function in ('dbms', 'web', 'app'))
declare @sql nvarchar(max) = 'select a,count(*),'+@count+' as count from l3_usage
where function in (''dbms'', ''web'', ''app'') '
exec(@sql)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.