2016-09-01 5 views
1
id  Status  Material Week 
------------------------------------- 
a1  Clear  iron  33 
a1  Clear  iron  34 
a1  Shipped  iron  35 
b1  Cancel  Brass  33 
b1  Cancel  Brass  34 
b1  Cancel  Brass  35 
c1  Identify Plastic  34 
c1  Clear  Plastic  35 

こんにちは、私は状況や材質のものが週33の間で変更した場合は週34週35との間に変更されたすべてのこれらのIDを選択することができ、クエリを思い付くしようとしていますし、 34または33と35は無視してください。また、第33週または第34週には存在しないが第35週に存在するものが含まれていなければならない。最後にIDは一意でなければなりません。比較行

これまでのところ、私は次のクエリを考え出しました。

SELECT DISTINCT t1.id 
FROM table t1 
JOIN table t2 
ON t1.id = t2.id 
WHERE t1.Status<>t2.Status or t1.Material<>t2.Material 

期待される結果:

id 
a1 
c1 
+0

希望の結果はどのように見えますか? – Strawberry

+0

期待される結果は a1とc1 – r0xette

答えて

0

ありますか?

SELECT 
T1.id 
FROM t T1 
LEFT JOIN t T2 ON T1.id = T2.id 
AND T2.Week = 34 
WHERE T1.Week = 35 
AND IF(T2.id IS NULL, TRUE, ((T1.Status <> T2.status) OR (T1.Material <> T2.Material))) 

Demo here


ちょうど2つのインスタンスT1 (row for week #35)T2 (row for week #34)

T2.week = 34 

T1.week = 35 

そして週の行が#34が、その後存在する場合を取るのいずれかstatusまたは012のmaterial出力に表示されるには、とT2が異なる必要があります。 上記のクエリでIFステートメントに


テスト参照してください:

create table t(
    id varchar(10), 
    Status varchar(10), 
    Material varchar(10), 
    week int 
); 

INSERT INTO t(id,status,material,week) 
VALUES('a1','clear','iron',33), 
('a1','clear','iron',34), 
('a1','shipped','iron',35), 
('b1','cancel','brass',33), 
('b1','cancel','brass',34), 
('b1','cancel','brass',35), 
('c1','identify','plastic',34), 
('c1','clear','plastic',35); 

を出力:

id 
a1 
c1 
+1

これは私のために働いた。ありがとうございました。 – r0xette

0

(行の変更は、あなたがIDによって行、より多くを持っている場合)の週は、文字列の試みである場合は、最終的に

select t.id from (
    select distinct id, status, material 
    from mytable 
    where week in (33,34,35)) t 
group by t.id 
having count(*) >1; 

を、カウントを使用することができます使用方法:

select t.id from (
    select distinct id, status, material 
    from mytable 
    where week in ('33','34','35')) t 
group by t.id 
having count(*) >1; 
+0

です。このクエリは私にとってはまったく機能しません。テーブルにidカラムを持っているにもかかわらず、idは未知のカラムだと言います。 – r0xette

+0

カラムに別名tablenameを使用して答えを少し更新しました。 – scaisEdge

+0

ありがとうございました。あなたの質問には、共通のIDだけが与えられます。 35週目に挿入されたが、33週目と34週には挿入されていないIDも必要であることを覚えておいてください。 – r0xette

0

このパズルの最後の部分として残されています読者のための練習...

SELECT x.*, y.* 
    FROM my_table x 
    LEFT 
    JOIN my_table y 
    ON y.id = x.id 
    AND (y.status = x.status AND y.material = x.material) 
    AND y.week = 35 
WHERE x.week = 34;