查找Nvarchar列的单词出现次数的百分比

时间:2016-07-28 12:55:22

标签: sql sql-server

我对SQL有点新,但我想弄清楚如何找到Nvarchar列中某些单词出现的次数。

标题为Location的列有6个可能的值:

  • 主页
  • 家庭健康
  • SNF
  • 急性
  • 其他
  • 未知

我想知道HomeHome Health出现的时间百分比。

我的查询看起来像这样。

Select 
    Year,
    (Select Count (Location Where Location = 'Home' or 'Home Health")/Count(Location))
From Database

3 个答案:

答案 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