动态情况时
SELECT
COUNT(id), AgeRange
FROM
(
select
id,
case
when age < 0 then 'less than 0'
when age >= 0 and age <=30 then '0-30'
when age >= 31 and age <=60 then '31-60'
when age >= 61 and age <=90 then '61-90'
when age >= 91 then '91+'
when age = null then 'NO INFORMATION'
else 'no catagory'
end AS AgeRange
from queue
where DATE between '01-Apr-2011' and '05-May-2011'
) T
GROUP BY
AgeRange;
我希望这些年龄范围(0-30、31-60、61-90)是动态的。这意味着这些值应该来自表(因为这些值是由用户设置的)。用户可以设置任意数量的值以获得结果。我怎样才能做到这一点?
SELECT
COUNT(id), AgeRange
FROM
(
select
id,
case
when age < 0 then 'less than 0'
when age >= 0 and age <=30 then '0-30'
when age >= 31 and age <=60 then '31-60'
when age >= 61 and age <=90 then '61-90'
when age >= 91 then '91+'
when age = null then 'NO INFORMATION'
else 'no catagory'
end AS AgeRange
from queue
where DATE between '01-Apr-2011' and '05-May-2011'
) T
GROUP BY
AgeRange;
I want these ageRanges (0-30, 31-60, 61-90) to be dynamic. it means these values should come from a table(as these are set up by user). user can set as many values as they want for getting result. How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您有第二个表,例如:
您可以执行类似的操作。
如果你想坚持你的案例陈述,你就必须让陈述充满活力。这意味着首先生成查询,将其存储到变量中,最后执行它。那是更多的工作!
Assuming you have a second table like:
The you could do something like this.
If you want to stick to your case-statement, you would have to make the statement dynamic. Which means generate first the query, store it into a variable and execute it at last. That is more work!
这是另一个尝试:动态 SQL,它不是最终的答案,但您已经了解了。
该代码是MySQL的,所以你不能复制它。但想法是一样的。将语句准备为字符串,然后执行它。
Here is another try: Dynamic SQL, it's not the finished answer, but you get the idea of it.
The code is for MySQL, so you cannot copy it. But the idea is the same. Prepare your statement as string and then execute it.