2016-05-05 17 views
-1

假設我們在ID1,ID2和ID3之間有層次關係。對於每個ID3,我們有7天的工作時間槽即。開始和結束。對於大多數部分來說,所有日子的開始和結束時間都是一樣的。構建條件SQL,可以突出顯示不同工作時間的日子

ID1 -> Multiple ID2 
ID2 -> Multiple ID3 
ID3 -> Min 7 records 

我想查詢和查找具有至少一天不同開始和結束時間的ID1。

我試過使用group by和distinct在ID3表上並將其嵌套回ID1,但它似乎不是一種有效的方法。

我可以使用加入有條件方法的棍棒嗎?

- 謝謝。

其他詳細信息:有3個獨立的表,ID1,ID2和ID3作爲他們的PK。

可以說ID1是BusinessID,ID2是LineOfBusiness,ID3是StoreID。現在每個StoreID在ID3Table中有7天的存儲打開和關閉時間。

我期待找到2個LineOfBusiness在不同時間運行的businessID。

我試着把開始時間和結束時間的組合分開,並根據計數對結果進行分組。我的意思是少於7意味着某一天是不同的。我把ID拿回了相應的ID1。這種方法使用嵌套查詢。

我希望能找到基於Join的解決方案。

希望這可以增加問題的清晰度。謝謝!

+3

對不起,問題沒有任何意義,我。你的數據結構是 – shawnt00

+0

? 「突出顯示」與查詢有什麼關係? –

+0

'GROUP BY ID3 HAVING MIN(starttime)<> MAX(starttime)'? – dnoeth

回答

0

如果您只需要信息在業務線這種情況發生使用group byhaving

select t1.id1, t1.name, t2.id2, 
     min(t3.dt1) as dt1_min, min(t3.dt2) as dt2_min, 
     max(t3.dt1) as dt1_max, max(t3.dt2) as dt2_max 
    from t1 
    join t2 on t2.id1 = t1.id1 
    join t3 on t3.id2 = t2.id2 
    group by t1.id1, t1.name, t2.id2 
    having min(t3.dt1) <> max(t3.dt1) or min(t3.dt2) <> max(t3.dt2) 
    order by t1.id1, t2.id2 

輸出:

ID1 NAME  ID2 DT1_MIN  DT2_MIN  DT1_MAX  DT2_MAX 
---- ---------- ---- ----------- ----------- ----------- ----------- 
    2 BUSINESS2 21 2015-01-25 2015-01-30 2015-02-01 2015-02-17 

如果你想詳細使用min()max()analytic版本:

select id1, name, id2, id3, dt1, dt2 
    from (
    select t1.id1, t1.name, t2.id2, t3.id3, t3.dt1, t3.dt2, 
      min(dt1) over (partition by t1.id1, t2.id2) as dt1_min, 
      min(dt2) over (partition by t1.id1, t2.id2) as dt2_min, 
      max(dt1) over (partition by t1.id1, t2.id2) as dt1_max, 
      max(dt2) over (partition by t1.id1, t2.id2) as dt2_max 
     from t1 
     join t2 on t2.id1 = t1.id1 
     join t3 on t3.id2 = t2.id2) 
    where dt1 <> dt1_min or dt1 <> dt1_max 
    or dt2 <> dt2_min or dt2 <> dt2_max 
    order by id1, id2, id3 

輸出:

ID1 NAME  ID2 ID3 DT1   DT2 
---- ---------- ---- ---- ----------- ----------- 
    2 BUSINESS2 21 211 2015-01-25 2015-01-30 
    2 BUSINESS2 21 212 2015-01-25 2015-01-30 
    2 BUSINESS2 21 213 2015-02-01 2015-02-17 

測試數據:

create table t1 (id1 number(3), name varchar2(10)); 
insert into t1 values (1, 'BUSINESS1'); 
insert into t1 values (2, 'BUSINESS2'); 

create table t2 (id2 number(3), id1 number(3)); 
insert into t2 values (11, 1); 
insert into t2 values (12, 1); 
insert into t2 values (21, 2); 
insert into t2 values (22, 2); 

create table t3 (id3 number(3), id2 number(3), dt1 date, dt2 date); 
insert into t3 values (111, 11, date '2015-01-25', date '2015-01-30'); 
insert into t3 values (112, 11, date '2015-01-25', date '2015-01-30'); 
insert into t3 values (211, 21, date '2015-01-25', date '2015-01-30'); 
insert into t3 values (212, 21, date '2015-01-25', date '2015-01-30'); 
insert into t3 values (213, 21, date '2015-02-01', date '2015-02-17'); 
相關問題