sql - SQL Server 中的文本/字符串分析

标签 sql sql-server string sql-server-2008 text

我正在尝试分析 SQL Server 中的大量文本,以根据两个不同表中重复单词的数量计算总体得分。我正在寻找一个查询来执行此操作。

为了方便起见,我在下面展示了示例。

表 1:

id | Message                   | 
--  ---------------------------
 1 | mike magic                | 
 2 | sky blue and dark         |
 3 | wars star                 | 
 4 | whistle mountain broke    |  

表 2(加号):

id | Words        | score
--  -------------- ------
 1 | mike         | +1
 2 | dark         | +1
 3 | wars         | +1

表 3(减号):

id | Words        | score
--  -------------- ------
 1 | whistle      | -1
 2 | mountain     | -1
 3 | magic        | -1

期望的结果:

id | Message                   | plus| minus| sum |
--  --------------------------- ----- ------ -----
 1 | mike magic                |  +1 | -1   |  0  |
 2 | sky blue and dark         |  +1 |  0   | +1  |
 3 | wars star                 |  +1 |  0   | +1  | 
 4 | whistle mountain broke    |   0 | -2   | -2  |

最佳答案

您可以使用以下查询:

--create table table1 (id int,message varchar(100),[date] date ,[other info] varchar(100));
--insert into table1 values
--(1,'mike magic', '2016-01-01','some other information'),
--(2,'sky blue and dark', '2016-01-02','some other information'),
--(3,'wars star', '2016-10-01','some other information'),
--(4,'whistle mountain broke', '2016-02-01','some other information');
--create table table2 (id int,words varchar(100), score int);
--insert into table2 values
--(1,'mike','+1'),
--(2,'dark','+1'),
--(3,'wars','+1');

--create table table3 (id int,words varchar(100), score int);
--insert into table3 values
--(1,'whistle','-1'),
--(2,'mountain','-1'),
--(3,'magic','-1');

select 
    t1.id, t1.message, t1.date,t1.[other info], 
    isnull(sum(cast(t2.score as int)),0) plus, 
    isnull(sum(cast(t3.score as int)),0) minus,
    isnull(sum(cast(t2.score as int)),0) + isnull(sum(cast(t3.score as int)),0) [sum]

from 
    table1 t1 
        left join table2 t2 
                on ' '+ t1.message+' ' like '% '+t2.Words+' %'
        left join table3 t3 
                on ' '+ t1.message+' ' like '% '+t3.Words+' %'
group by t1.id, t1.message, t1.date,t1.[other info]

关于sql - SQL Server 中的文本/字符串分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36558164/

相关文章:

sql - 如何对数据中包含 '%'的列执行Like in SQL?

c# - 检查数值精度和小数位数的有效方法是什么?

java - 检索数据时出错

sql - 不使用 CTE 的父子层次结构路径

java - 在字符串中查找数据

c++ - 使用 wstring 获取行读取文件

没有三角函数的 SQL 距离查询

sql - 如何在没有安装 dev 库的情况下在 C 中使用 sqlite3?

python - 如何测试字符串的一部分是否等于python列表中的项目?

sql - 比较单列 oracle 中的多个值