【问题标题】:GROUP BY members of a comma delimited listGROUP BY 逗号分隔列表的成员
【发布时间】:2012-10-25 14:36:57
【问题描述】:

我有一个数据表如下:

t1
____________________________________________________
resources          | companyName | Response | Score 
David, Matt        |  companyA   |  YES     |   5
Matt               |  compqanyB  |  NO      |   8
Kyle, Kyle, David  |  companyC   |  YES     |   2

如您所见,resources 是一个逗号分隔的字符串。此外,并非resources 的所有成员都必须是唯一的(参见第 3 行)。

我想GROUP BY 任何列表中的每个DISTINCT 成员。所有其他列将被聚合。

预期结果:

query
______________________________________________________________________________
resources     |  companyName        |    Response         | Score
David         | *agregated result*  | *agregated result*  | *agregated result*  
Matt          | *agregated result*  | *agregated result*  | *agregated result*  
Kyle          | *agregated result*  | *agregated result*  | *agregated result*  

编辑:

另一种可能性:

query
____________________________________________________
resources          | companyName | Response | Score 
David              |  companyA   |  YES     |   5
Matt               |  companyA   |  YES     |   5
Matt               |  compqanyB  |  NO      |   8
Kyle               |  companyC   |  YES     |   2
David              |  companyC   |  YES     |   2

【问题讨论】:

  • 我不认为你可以用纯 SQL 做到这一点,但在任何编程语言(php、java 等)中应该不会太难
  • 我将其用于报告服务,因此我尝试直接访问数据库。如果没有必要,我宁愿不使用中间人。但如果这不可能,那我想我必须这样做。
  • 您可以在 SQL 中执行此操作,但您必须使用游标。这更像是对真实编程语言的 SQL 模仿,所以我宁愿不去那里。
  • 最终结果是让每个资源都获得与它们相关联的票证的分数。我编辑了我的 OP,这个新方向可能吗?每个资源都有另一行?
  • 我想这真的只是同一个问题,没有GROUP BY

标签: mysql sql tsql


【解决方案1】:

让我假设您有一个包含各个名称的资源表。在这种情况下,您可以使用以下查询来做您想做的事情:

select r.name, <other aggregated results>
from t1 join
     Resources r
     on concat(', ', t1.resources, ', ') like concat(', %', r.name, ', %')
group by r.name

如果您没有资源表,您可能应该这样做。将这些东西存储在逗号分隔的列表中通常是一个坏主意。如果数据没有被规范化并且出现拼写错误,这是一个特别糟糕的主意。

【讨论】:

  • 不幸的是,我被这个数据库卡住了。我没有创建它。而且我相信我确实有一个资源名称表。让我试试这个。
  • 这太棒了。谢谢。
猜你喜欢
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
  • 2013-10-20
  • 1970-01-01
  • 2013-07-03
相关资源
最近更新 更多