0

我正在尝试构建一个查询来查看我们的帮助台系统中的票证。我想在主题或描述字段中搜索一些关键字,即“电子邮件”,并返回每个关键字的计数。下面是一个示例表。还有一个类别行,但是维护得不好,所以大部分字段都是空的。

  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

最简单的方法是什么?

4

2 回答 2

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

请参阅带有演示的 SQL Fiddle

如果您想要查询的类别列表较长,那么您可能需要考虑将其存储在单独的表中并加入该表。

为 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

请参阅带有演示的 SQL Fiddle

于 2012-08-22T19:01:24.000 回答
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
于 2012-08-22T18:57:24.760 回答