Remove query results with having
I have an SQL query like the following:
select aaa,
count(condition_1),
count(condition_2),
count(condition_3)
from DB
where ...
group by 1,
order by 1
The above will return four columns. Is it possible with a having statement to suppress some of the fields in the results but return all the rows that the original script would produce.
Thanks in adv开发者_运维技巧ance for your help
if you are trying to "suppress" field values (and i assume that you're really looking to return 0 in that case, since the fields aren't going away as long as they're in the select) based on some criteria but return all rows, you could try the following:
select aaa,
case when count(condition_1) > 1 then count(condition_1) else 0 end as count_1,
case when count(condition_2) > 1 then count(condition_2) else 0 end as count_2,
case when count(condition_3) > 1 then count(condition_3) else 0 end as count_3
from DB
where ...
group by 1,
order by 1
obviously modify the case statements to reflect the values you wish to return, with all others being 0
I am not exactly sure what you mean but, from my understanding you are trying to group your results based on a single column's count. If that's right, then the code you need would be along the lines of
select aaa,
count(condition_1) as count_1,
count(condition_2) as count_2,
count(condition_3) as count_3
from DB
where ...
group by 1,
order by 1
having count_1 > 1
No, you can't suppress columns (fields) and keep all the rows.
Any filtering (WHERE, HAVING etc) will apply only to rows.
You could do this
select
aaa,
case
when somecondition then count(condition_1)
when somecondition then count(condition_2)
end as thecount,
case
when somecondition then '1'
when somecondition then '2'
end as thecountofwhat
from mytable
where ...
group by aaa,
order by aaa
Note: don't use ordinals in GROUP BY or ORDER BY. Bad practice. And only MySQL allows such nonsense in the GROUP BY.
精彩评论