问题
I'm trying to count the number of conditions from a set number of 100 results.
Example: Of the last set 100 actions, how many were for 'X'?
I'm not quite sure where to start.
I'm fairly new to SQL, and I've tried inner joins, subqueries, etc, but I just can't seem to figure it out. I feel it's something fairly simple.
Thank you!
回答1:
To do this, you simply need to sum
up a case
statement that checks for the value. However, if you want to do this for only 100 rows, you will need to perform this query against a derived table
(or a Common Table Expression, if your RDBMS supports it) to do that row count restriction.
Here is an example that should work in most RDBMSes (you may need to replace TOP
with LIMIT
, depending on your RDBMS):
select
sum(
case
when (my_val='X') then
1
else
0
end
)
from
(
select top 100
my_val
from
my_table
) t
回答2:
@RToyo's answer covers it for any DBMS.
In Snowflake you can slightly simplify it by using IFF:
select
sum(IFF(my_val='X', 1, 0))
from
(
select top 100
my_val
from
my_table
) t
来源:https://stackoverflow.com/questions/55656838/how-do-i-set-a-number-of-rows-and-count-the-conditional-results