SQL根据特定值的行数打印值

时间:2017-01-16 09:17:22

标签: sql oracle oracle11g

我有三张表格如下:

--------------------------
Account Number | AGR ID
--------------------------
111               1234
222               2234
---------------------------

 --------------------------
AGR Number | Meter ID
--------------------------
1234              123
2234              223
---------------------------
---------------------------
Meter ID | Meter Read Date
---------------------------
123        2016-01-17
123        2016-03-13
223        2016-11-23

现在我需要根据第三张表中可用的仪表读数来打印帐户ID和值。

对于上述数据,我需要输出如下:

----------------------------------
Account ID  |  Is multiple reads
----------------------------------
111            Y
222            N

1 个答案:

答案 0 :(得分:5)

GROUP BYCASE应该足够了

select
    t1.Account_Number,
    case when count(*) > 1 then 'Y' else 'N' end Is_multiple
from table1 t1
inner join table2 t2
on t1.meter_id = t2.meter_id
group by t1.Account_Number;

编辑:

根据修改后的架构,这应该有效:

select
    t1.Account_Number,
    case when count(*) > 1 then 'Y' else 'N' end Is_multiple
from table1 t1
inner join table2 t2
on t1.agr_id = t2.agr_id
inner join table3 t3
on t2.meter_id = t3.meter_id
group by t1.Account_Number;