0

I am just starting learn SQL at work, but I am having trouble with subquerys. I am hoping for not just a Query, but an explanation of how to create subqueries.

Current SQL Query

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

Returns

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

What I need

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

Thanks

Database has 3 columns: Timestamp, Count, Latency Type

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

Each timestamp has a 1m, 2m, and 4m latency but these are all different rows.

I need to return one row that is timestamp, count for 1m at timestamp, count for 2m at timestamp, count for 4m at timestamp

I can't change the database to instead of count1m column count2m column etc.

A different way of looking at it is merging these three queries into one

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\')
4

1 回答 1

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')
于 2012-04-20T18:39:31.033 回答