我正在尝试构建一个查询来查看我们的帮助台系统中的票证。我想在主题或说明字段中搜索几个关键字,即“电子邮件”,并返回每个关键字的计数。下面是一个示例表。还有一个类别行,但它没有很好地维护,因此大多数字段都是空的。
ID | Subject | Description
-----+-------------------------------------
1 | hellloooo | can't send email
2 | email down? | can't get to intranet
3 | Phone trouble | can't check voicemail
4 | Using my phone | I don't know how
5 | Need new mouse | please replace
6 | Mouse acting funny | n/a
7 | Intranet won't Load | what's this plug do?
8 | not getting voicemail | why not?
我想返回类似
的内容Category | # of tickets
---------------------------
Email | 3
Phone | 2
Intranet | 2
最简单的方法是什么?
答案 0 :(得分:1)
您没有指定RDBMS,但以下内容适用于SQL Server
;with cte as
(
select 'Email' Category
UNION ALL
select 'Phone'
UNION ALL
select 'Intranet'
)
select category, count(*)
from cte c
inner join tickets t
on t.subject like '%' + c.category + '%'
or t.description like '%' + c.category + '%'
group by category
如果您要查询的类别列表较长,则可能需要考虑将其存储在单独的表中并加入表中。
编辑Sqlite,没有CTE所以你可以通过以下方式做我的例子(更新后使用正确的语法在SQLite中连接):
select category, count(*)
from
(
select 'Email' Category
UNION ALL
select 'Phone'
UNION ALL
select 'Intranet'
) c
inner join tickets t
on t.subject like '%' || c.category || '%'
or t.description like '%' || c.category || '%'
group by category
答案 1 :(得分:0)
使用Microsoft SQL Server,我可能会这样做:
DECLARE @CategoryList TABLE (Category VARCHAR(MAX))
INSERT INTO @CategoryList VALUES ('Email')
INSERT INTO @CategoryList VALUES ('Phone')
INSERT INTO @CategoryList VALUES ('Intranet')
SELECT Category, COUNT(*) AS NumberOfTickets
FROM Tickets
INNER JOIN @CategoryList CategoryList ON Tickets.Subject LIKE '%' + CategoryList.Category + '%' OR Tickets.Description LIKE '%' + CategoryList.Category + '%'
GROUP BY Category