我对SQL有点新,但我想弄清楚如何找到Nvarchar列中某些单词出现的次数。
标题为Location
的列有6个可能的值:
我想知道Home
和Home Health
出现的时间百分比。
我的查询看起来像这样。
Select
Year,
(Select Count (Location Where Location = 'Home' or 'Home Health")/Count(Location))
From Database
答案 0 :(得分:0)
这是每年选择多少次Home& Home Heath在数据库中
select Year, Location, count(*)
From Database where Location in ('Home', 'Home Health')
group by Year, location
这是计算百分比
select Year, Location, CAST(count(*) as decimal) * 100 / (select count(*) from Location)
From Database where Location in ('Home', 'Home Health')
group by Year, location
答案 1 :(得分:0)
使用以下查询,您应该获得每个年份和位置的百分比四舍五入到表格中的整数元素:
SELECT Year, Location,
round( count(*) * 100.0 / (SELECT count(*) FROM Database) , 1)
FROM Database
GROUP BY Year, Location
答案 2 :(得分:0)
下面,您将看到包含样本数据的示例表。然后我声明变量以捕获行数和我们匹配匹配单词的次数。最后,我添加了NULLIF语法,以防止在表中没有记录时出现被零除错误。
CREATE TABLE ##test1
(location VARCHAR(50))
INSERT INTO ##test1
VALUES ('home'), ('office'),('work'),('home office'),('apartment'),('home health')
DECLARE @instancecount DECIMAL (12,4) = (SELECT COUNT(location) FROM ##test1 where Location in ('Home', 'Home Health'))
DECLARE @totalcount DECIMAL (12,4) = (SELECT COUNT(location) FROM ##test1)
SELECT (@instancecount/NULLIF(@totalcount,0))
DROP TABLE ##test1