我正在尝试从调查客户的电话中提取计数。该调查有3个问题,答案有时是数字的,有时是单词。我想计算答案,但需要计算任何数值并将其显示为NUMERIC_ENTRY。我一直在尝试“ IsNumeric”和“ Case when”,但结果无法正确显示。
样本数据:
Question | Answer
Q1 | 12
Q1 | 456
Q1 | 8
Q1 | DontKnow
Q1 | TellMeHow
Q2 | Yes
Q3 | No
采样结果:
Question | Asnwer | Count
Q1 | NUMERIC_ENTRY | 3
Q1 | DontKnow | 1
Q1 | TellMeHow | 1
Q2 | Yes | 1
Q3 | No | 1
示例SQL:
select Question, Answer, count (*) from Survey
where Client = 'ABC_Company'
group by Question, Answer
答案 0 :(得分:0)
使用TRY_PARSE
函数,前提是您的版本是 SQL Server 2012或更高版本( @Gordon正确使用ISNUMERIC
函数可能会出现问题,如下面的演示链接所示):
select q.Question, q.AnswerCount, count(q.AnswerCount) as count
from
(
select Question,
(case when TRY_PARSE(Answer as int) is not null then 'NUMERIC_ENTRY'
else Answer end) as AnswerCount
from Survey
where Client = 'ABC_Company'
group by Question, Answer
) as q
group by q.Question, q.AnswerCount
order by q.Question, count desc
答案 1 :(得分:0)
您可以使用LIKE
和与任何非数字字符匹配的模式。
SELECT question,
CASE
WHEN answer = ''
OR answer LIKE '%[^0-9]%'
answer
ELSE
'NUMERIC_ENTRY'
END answer,
count(*)
FROM survey
WHERE client = 'ABC_Company'
GROUP BY question,
CASE
WHEN answer = ''
OR answer LIKE '%[^0-9]%'
answer
ELSE
'NUMERIC_ENTRY'
END;
(假设SQL Server是由于isnumeric()
(您也可以使用,但是众所周知,有时会产生有趣的结果,我宁愿选择LIKE
)。)
SQL Server 2012以来的另一个选项是使用try_cast()
,以检查字符串是否可以转换为整数。
SELECT question,
CASE
WHEN answer = ''
OR try_cast(answer AS integer) IS NULL
answer
ELSE
'NUMERIC_ENTRY'
END answer,
count(*)
FROM survey
WHERE client = 'ABC_Company'
GROUP BY question,
CASE
WHEN answer = ''
OR try_cast(answer AS integer) IS NULL
answer
ELSE
'NUMERIC_ENTRY'
END;
答案 2 :(得分:0)
对于MySQL:从https://stackoverflow.com/a/5065007/2469308开始,您可以使用If()函数检查字符串是否为数字。
尝试以下查询:
select Question,
IF(CONCAT('',Answer * 1) = Answer, 'NUMERIC_ENTRY', Answer) AS Ans,
COUNT(*)
FROM Survey
where Client = 'ABC_Company'
GROUP BY Question, Ans
答案 3 :(得分:0)
请勿使用isnumeric()
。您会对某些被认为是数字的事物感到惊讶(例如'$'
,','
和'3e2'
)。
因此,在这种情况下,like
是您的朋友。假设numeric
是指所有数字。由于您想按结果进行汇总,因此需要两次引用该列。因此,我将建议apply
:
select s.question, v.answer_group, count(*)
from survey s cross apply
(values (case when s.answer like '%[^0-9]%' then s.answer -- has non-digit
else 'NUMERIC_ENTRY'
end)
) v(answer_group)
group by s.question, v.answer_group
order by s.question, count(*) desc, v.answer_group;
请注意,这会将空字符串视为数字。这很容易调整;您的问题不清楚在这种情况下该怎么做。我可能会建议:
(values (case when ltrim(rtrim(s.answer)) = '' or s.answer is null then 'BLANK_ENTRY'
when s.answer like '%[^0-9]%' then s.answer -- has non-digit
else 'NUMERIC_ENTRY'
end)
) v(answer_group)