SQL查询帮助 - 子查询/嵌入查询

时间:2012-04-20 18:32:15

标签: sql oracle

我刚刚开始在工作中学习SQL,但我遇到了subquerys的问题。 我希望不仅仅是一个查询,而是一个如何创建子查询的解释。

当前SQL查询

SELECT to_char(P_DT, 'yyyy-mm-dd HH:mi:ss'), COUNT, LATENCY 
FROM latency ORDER BY P_DT

返回

to_char(P_DT, 'yyyy-mm-dd HH:mi:ss'), COUNT, LATENCY
2012-04-20 03:42:00     83659   1m
2012-04-20 03:42:00 70305   2m
2012-04-20 03:42:00 105194  4m
2012-04-20 03:43:00 70277   1m
2012-04-20 03:43:00 0   2m
2012-04-20 03:43:00 0   4m

我需要什么

to_char(P_DT, 'yyyy-mm-dd HH:mi:ss'), COUNT.LATENCY='1m', COUNT.LATENCY='2m', COUNT.LATENCY='4m'
2012-04-20 03:42:00 83659       70305      105194
2012-04-20 03:43:00 70227       0          0

由于

数据库有3列:时间戳,计数,延迟类型

Tmestamp = progressive timestamp for each min
Count = count, just a number
Latency Type = 1m, 2m or 4m

每个时间戳都有1米,2米和4米的延迟,但这些都是不同的行。

我需要返回一行 时间戳,在时间戳记计数为1米,在时间戳记计数为2米,在时间戳记计数为4米

我无法将数据库更改为count1m列count2m列等。

另一种看待它的方法是将这三个查询合并为一个

SELECT to_char(P_DT, \'yyyy-mm-dd HH:mi:ss\'), COUNT 
FROM LATENCY 
WHERE SOURCE_ID=\'2\' AND LATENCY = \'1m\' 
GROUP BY to_char(P_DT, \'yyyy-mm-dd HH:mi:ss\') 
ORDER BY to_char(P_DT, \'yyyy-mm-dd HH:mi:ss\')

SELECT to_char(P_DT, \'yyyy-mm-dd HH:mi:ss\'), COUNT 
FROM LATENCY 
WHERE SOURCE_ID=\'2\' AND LATENCY = \'2m\' 
GROUP BY to_char(P_DT, \'yyyy-mm-dd HH:mi:ss\') 
ORDER BY to_char(P_DT, \'yyyy-mm-dd HH:mi:ss\')

SELECT to_char(P_DT, \'yyyy-mm-dd HH:mi:ss\'), COUNT 
FROM LATENCY 
WHERE SOURCE_ID=\'2\' AND LATENCY = \'4m\' 
GROUP BY to_char(P_DT, \'yyyy-mm-dd HH:mi:ss\') 
ORDER BY to_char(P_DT, \'yyyy-mm-dd HH:mi:ss\')

1 个答案:

答案 0 :(得分:1)

如果我理解正确的话,应该这样做:

SELECT  to_char(P_DT, 'yyyy-mm-dd HH:mi:ss'), 
        SUM(CASE WHEN LATENCY = '1m' THEN COUNT ELSE 0 END) AS LATENCY1m, 
        SUM(CASE WHEN LATENCY = '2m' THEN COUNT ELSE 0 END) AS LATENCY2m, 
        SUM(CASE WHEN LATENCY = '4m' THEN COUNT ELSE 0 END) AS LATENCY4m
FROM latency 
GROUP BY to_char(P_DT, 'yyyy-mm-dd HH:mi:ss')
ORDER BY to_char(P_DT, 'yyyy-mm-dd HH:mi:ss')