我的表格列如下:
Table 1 (Instance Table):
Name | Id | Duration | ConfigurationID
Table 2 (Class Table):
Configuration | Id | Last Changed
在我的表2中,我有配置名称的行如下所示。名称是代码生成的。:
Test 1
Copy of Test 1
Copy of Test 1 (1)
Copy of Test 1 (2)
Copy of Test 1 (3)
...
...
Test 2
Copy of Test 2
Copy of Test 2 (1)
Copy of Test 2 (2)
Copy of Test 2 (3)
表1包含不同配置的实例。例如,行1-15可以是配置测试1,16-30测试配置副本实例等的实例。
我想找到配置类型的所有实例的平均持续时间及其所有副本,即行/列,如下所示:
Row/Column 1: Avg Duration of instances of type Test 1 and all of its copies (Copy of Test 1, Copy of Test 1(1), ...Copy of Test 1 (3));
Row/Column 2: Avg Duration of instances of type Test 2 and all of its copies (Copy of Test 1, Copy of Test 1(1), ...Copy of Test 1 (3));
....
我需要一些关于如何编写SQL查询来完成此任务的帮助。 到目前为止,我有这个:
SELECT AVG(i.[Duration]/1000.0) as [Avg Duration (s)]
FROM [Table 1] i
LEFT OUTER JOIN [Table 2] p
ON i.[ConfigurationID] = p.Id
WHERE i.Name LIKE '(Copy of)%'
GROUP BY i.Name
答案 0 :(得分:1)
SELECT AVG(i.Duration / 1000) as "Avg Duration (s)"
FROM "Table 1" i
LEFT JOIN "Table 2" p
ON i.ConfigurationID = p.Id
GROUP BY CASE
WHEN i.Name LIKE 'C%' THEN SUBSTRING_INDEX(SUBSTR(i.Name, 9), ' ', 2)
ELSE i.Name
END
“有趣”的部分是SUBSTRING_INDEX(SUBSTR(i.Name, 9), ' ', 2)
。
我们剪切了初始'Copy of '
,然后在第二个空格之前获取所有内容。
您的问题已标记为mysql和sql-server。这个答案使用mysql。