我有一个基于多个子查询计算值的查询。子查询基于特定时间戳。我想为许多不同时间戳的记录计算此值。我无法弄明白该怎么做。
基本公式为(S11S4CreateSessionReqRcvd - S11S4CreateSessionRespAccSent)* 100 / S11S4CreateSessionRespAccSent
SELECT
((((select ref_data FROM test.sgw_S5S11 where timestamp = "2013-08-21 00:00:06" and ref_type = "S11S4CreateSessionReqRcvd" ) - (select ref_data FROM test.sgw_S5S11
where timestamp = "2013-08-21 00:00:06" and ref_type = "S11S4CreateSessionRespAccSent")) * 100) / (select ref_data FROM test.sgw_S5S11
where timestamp = "2013-08-21 00:00:06" and ref_type = "S11S4CreateSessionReqRcvd")) as MyCalc
我不知道如何粘贴到表中,所以这里是csv格式的数据样本
这是我的数据样本。 (我不知道如何在这里放一张桌子,所以它是用CSV格式的)
mykey,timestamp,ref_type,ref_data 1016101," 2013-08-21 00:00:06",S5S8CreateSessionReqSent,128042907 1016102," 2013-08-21 00:00:06&# 34;,S5S8CreateSessionRespAccRcvd,127088838 1016103," 2013-08-21 00:00:06",S5S8CreateSessionRespRejRcvd,615553 1016104," 2013-08-21 00:00:06",S5S8CreateBearerReqRcvd ,10047 1016105," 2013-08-21 00:00:06",S5S8CreateBearerRespAccSent,9932 1016106," 2013-08-21 00:00:06",S5S8CreateBearerRespRejSent,103 1016107, " 2013-08-21 00:00:06",S11S4CreateSessionReqRcvd,128255390 1016108," 2013-08-21 00:00:06",S11S4CreateSessionRespAccSent,127114539 1016109," 2013-08-21 00:00:06",S11S4CreateSessionRespRejSent,713325 1016110," 2013-08-21 00:00:06",S11S4CreateBearerReqSent,10028 1016111," 2013-08- 21 00:00:06",S11S4CreateBearerRespAccRcvd,9932 1016112," 2013-08-21 00:00:06",S11S4CreateBearerRespRejRcvd,42
任何帮助都将非常感谢!!!
答案 0 :(得分:1)
此查询很难处理,因为您已在不同的行上存储了属性。这种设计称为实体 - 属性 - 值,对于关系数据库来说,这通常是一个坏主意。
以下查询可能更有效,更容易编写:
SELECT (eav.ReqRcvd - eav.AccSent) * 100 / eav.AccSent AS MyCalc
FROM (
SELECT timestamp,
MAX(IF(ref_type='S11S4CreateSessionReqRcvd', ref_data)) AS ReqRcvd,
MAX(IF(ref_type='S11S4CreateSessionRespAccSent', ref_data)) AS AccSent
FROM test.sgw_S5S11
WHERE timestamp = '2013-08-21 00:00:06'
GROUP BY timestamp
) AS eav;
PS:对单词引号'
使用字符串和日期文字,而不是双引号"
。在标准SQL中,双引号用于分隔表和列标识符。默认情况下,MySQL会将两种类型的引号视为相同,但这取决于SQL_MODE,如果您使用其他品牌的RDBMS,也不会采用相同的方式。因此,养成以标准方式使用引号的习惯是一件好事。