我正在尝试计算一个数字列表落入某个范围的次数。
数据:
advance:
--------
5000
5000
10125
5000
0
15000
[NULL]
7000
8000
[NULL]
7000
2275
6000
2000
4000
7000
4000
8000
使用case语句并在一个查询中计数。 案例陈述:
CASE
WHEN
advance > 10000
THEN
/* Display as 'High'*/
WHEN
advance >= 5000 and advance <= 10000
THEN
/*Display as 'Moderate'*/
WHEN
advance < 5000
THEN
/*Display as 'Low'*/
ELSE
/*Display as 'N/A'*/
END
但与此相关的是数据必须在单个单元格中格式化。 到目前为止我所拥有的:
"i. Category " + "Number" + char(13)+char(10) +
"ii. -----------------------------------" + char(13)+char(10) +
"iii. High: " + /*Display High*/ + char(13)+char(10) +
"iv. Low: " + /*Display Low*/ + char(13)+char(10) +
"v. Moderate: " + /*Display Moderate*/ + char(13)+char(10) +
"vi. N/A " + /*Display N/A */ +
所以最终结果应如下所示:
i. Category Number
ii. --------------------
iii. High 5
iv. Low
v. Moderate
vi. N/A
我正在使用Sybase编写此查询,通常我不会寻求帮助。我只是陷入困境,无法围绕这个缠绕我的大脑。感谢
答案 0 :(得分:2)
您可以使用GROUP BY
声明:
SELECT Category, Count(Category)
FROM (SELECT CASE
WHEN advance > 10000
THEN 'High' as Category
WHEN advance >= 5000 and advance <= 10000
THEN 'Moderate' as Category
WHEN advance < 5000
THEN 'Low' as Category
ELSE
'N/A' as Category
END
FROM your_table_name) as CategoriesResult
GROUP BY Category
如果您想生成单个文本值,可以将其包装到一个额外的查询中,并将最终结果集的每条记录追加到结果文本值中:
DECLARE @result AS VARCHAR(MAX)
SET @result = "i. Category Number" + char(13) + char(10) +
"ii. -----------------------------------" + char(13) + char(10)
SELECT @result = @result + CONVERT(varchar(8), Category)
+ " "
+ CONVERT(VARCHAR(8), CategoryCount) + char(13) + char(10)
FROM
(SELECT Category, Count(Category) as CategoryCount
FROM (SELECT CASE
WHEN advance > 10000
THEN 'High' as Category
WHEN advance >= 5000 and advance <= 10000
THEN 'Moderate' as Category
WHEN advance < 5000
THEN 'Low' as Category
ELSE
'N/A' as Category
END
FROM your_table_name) as CategoriesResult
GROUP BY Category
)SourceTable
答案 1 :(得分:0)
我不确定它有效,但我希望我的想法可以帮助你
select "i. Category " + "Number" + char(13)+char(10) +
"ii. -----------------------------------" + char(13)+char(10) +
"iii. High: " + cast((select count(1)
from tabData
where advance > 10000) as varchar) + char(13)+char(10) +
"iv. Low: " + cast((select count(1)
from tabData
where advance >= 5000
and advance <= 10000) as varchar) + char(13)+char(10) +
"v. Moderate: " + cast((select count(1)
from tabData
where advance < 5000) as varchar) + char(13)+char(10) +
"vi. N/A " + cast((select count(1)
from tabData
where advance is null) as varchar)