我正在尝试在ReportBuilder(数字隐喻,而不是微软)中创建一个报告,但我无法让SQL做我想做的事。
我有一个包含字段building
的表:
| building |
+------------+
| WhiteHouse |
| TajMahal |
和另一个包含字段locations
的表:
| id | locations |
+----+-----------------------------------------------------------------+
| 1 | WhiteHouse:RoseGarden,WhiteHouse:MapRoom,TajMahal:MainSanctuary |
| 2 | TajMahal:NorthGarden,WhiteHouse:GreenRoom |
我想创建一个表格,显示locations
中每个建筑物的使用次数,如下所示:
| building | count |
+------------+-------+
| WhiteHouse | 3 |
| TajMahal | 2 |
字符:
和,
从不用于建筑物或房间名称。即使是一个快速而肮脏的解决方案,假设建筑物名称永远不会出现在房间名称中,对我来说也足够了。
当然,这对于任何理智的编程语言来说都很容易(总计超过/\bWhiteHouse:/
);诀窍是让RB去做。建议您采取变通方法。
答案 0 :(得分:0)
在SQL Server中借助自定义sql split function
,可以使用“,”和“:”字符作为分隔符将位置字符串拆分为多个部分select
p2.val,
count(p2.val)
from locations l
cross apply dbo.split(l.locations,',') p1
cross apply dbo.split(p1.val,':') p2
inner join building b
on b.building = p2.val
group by p2.val
我不确定mysql中是否有类似的,如果是这样,请检查以下解决方案作为模板
答案 1 :(得分:0)
你可以试试这个,可能不是最快,但肯定更容易的解决方案。
SELECT t1.building,
( SELECT SUM( ROUND( (LENGTH(t2.locations)
- LENGTH(REPLACE(t2.locations, concat(t1.building, ':'), ''))
) / (LENGTH(t1.building) + 1)
)
)
FROM table2 AS t2
) as count
FROM table1 as t1