连接两个表在sql oracle中添加选择性数据

时间:2013-01-16 04:22:48

标签: sql oracle

这些是我的表

C_ID  USAGE B_ID
4     100   2
2     400   1
3     200   2
1     300   1

B_ID  ZONE_NAME
2     central
1     west

这是我的查询,

select 
    sum(usage)  
from 
(
    select 
        usage_679.c_id,
        usage_679.b_id,usage_679.usage,
        zone_679.zone_name 
    from usage_679 inner join zone_679
        on zone_679.b_id = usage_679.b_id
)
where zone_name like 'w%';

问题是它只能打印与西区相关的数据。我想在相应的区域中打印两个区域名称和总使用量。

预期产出

zone_name  sum(usage)
1            700
2            300

3 个答案:

答案 0 :(得分:1)

这是SQL FILLDE LINK FOR SAMPLE EXECUTION。您不需要 WHERE 条件。您可以通过 GROUP BY

来实现
select 
    sum(usage),zone_name  
from 
(
    select 
        usage_679.c_id,
        usage_679.b_id,usage_679.usage,
        zone_679.zone_name 
    from usage_679 inner join zone_679
        on zone_679.b_id = usage_679.b_id
)
group by  zone_name

<强>输出

| SUM(USAGE) | ZONE_NAME |
--------------------------
|        700 |      west |
|        300 |   central |

即使这样也可以:(不需要2个选择)

SELECT
    sum(USAGE),zone_name

    FROM usage_679 INNER JOIN zone_679
        ON zone_679.b_id = usage_679.b_id

GROUP BY  zone_name

<强>输出:

| SUM(USAGE) | ZONE_NAME |
--------------------------
|        700 |      west |
|        300 |   central |

答案 1 :(得分:0)

您可以使用GROUP BY子句来获得结果。请试试。

select 
    zone_679.zone_name,
    zone_679.b_id,
    SUM(usage_679.usage)
from usage_679 inner join zone_679
    on zone_679.b_id = usage_679.b_id 
group by zone_679.zone_name, zone_679.b_id;

答案 2 :(得分:0)

添加@priyanks答案...如果您只想要西方的结果,请添加having条款,即

SELECT
sum(USAGE),zone_name

FROM usage_679 INNER JOIN zone_679
    ON zone_679.b_id = usage_679.b_id

GROUP BY  zone_name
HAVING zone_name like 'w%' --Filter added for result