これは、一致しない可能性のあるunpivotとのマッチングペアの問題、または複数のマッチのように見えます。行番号を割り当てると、 の可能性があります。
/*> drop table if exists t;
/*> create table t (
/*> WeekID int, ISModelled varchar(10), ProductID int, Units int, Value int);
/*> insert into t values
/*> (1 , 'MODEL' , 123 , 0 , 0),
/*> (2 , 'EPOS' , 123 , 0 , 0),
/*> (2 , 'MODEL' , 123 , 100 , 50),
/*> (3 , 'IMPUTE' , 987 , 100 , 50),
/*> (4 , 'MODEL' , 123 , 100 , 50),
/*> (4 , 'EPOS' , 987 , 100 , 50),
/*> (4 , 'EPOS' , 123 , 100 , 50),
/*> (5 , 'EPOS' , 987 , 0 , 0),
/*> (5 , 'MODEL' , 987 , 100 , 50);
/*> */
MariaDB [sandbox]> select S.* from
-> (
-> select t.ISModelled Smodelled,
-> t.* ,
-> if(t.WeekID <> @pw ,@rne:=1,@rne:[email protected]+1) rne,
-> @pw:=t.weekid
-> from (select @rne:=0,@pw:=0) rn,t
-> where t.ismodelled = 'EPOS' and t.units = 0 and t.Value = 0
-> order by t.weekid
->) s
-> join
-> (
-> select t.ISModelled Mmodelled,
-> t.* ,
-> if(t.WeekID <> @pw ,@rne:=1,@rne:[email protected]+1) rne,
-> @pw:=t.weekid
-> from (select @rne:=0,@pw:=0) rn,t
-> where t.ismodelled = 'MODEL' and t.units > 0 and t.Value > 0
-> order by t.weekid
->) t on t.weekid = s.weekid and t.rne = s.rne and t.productid = s.productid
-> where Smodelled = 'EPOS'
-> union ALL
-> select T.* from
-> (
-> select t.ISModelled Emodelled,
-> t.* ,
-> if(t.WeekID <> @pw ,@rne:=1,@rne:[email protected]+1) rne,
-> @pw:=t.weekid
-> from (select @rne:=0,@pw:=0) rn,t
-> where t.ismodelled = 'EPOS' and t.units = 0 and t.Value = 0
-> order by t.weekid
->) s
-> join
-> (
-> select t.ISModelled Mmodelled,
-> t.* ,
-> if(t.WeekID <> @pw ,@rne:=1,@rne:[email protected]+1) rne,
-> @pw:=t.weekid
-> from (select @rne:=0,@pw:=0) rn,t
-> where t.ismodelled = 'MODEL' and t.units > 0 and t.Value > 0
-> order by t.weekid
->) t on t.weekid = s.weekid and t.rne = s.rne and t.productid = s.productid
-> where Mmodelled = 'MODEL'
-> ORDER BY WEEKID,ISMODELLED,RNE
->
->
->
-> ;
+-----------+--------+------------+-----------+-------+-------+------+---------------+
| Smodelled | WeekID | ISModelled | ProductID | Units | Value | rne | @pw:=t.weekid |
+-----------+--------+------------+-----------+-------+-------+------+---------------+
| EPOS | 2 | EPOS | 123 | 0 | 0 | 1 | 2 |
| MODEL | 2 | MODEL | 123 | 100 | 50 | 1 | 2 |
| EPOS | 5 | EPOS | 987 | 0 | 0 | 1 | 5 |
| MODEL | 5 | MODEL | 987 | 100 | 50 | 1 | 5 |
+-----------+--------+------------+-----------+-------+-------+------+---------------+
4 rows in set (0.00 sec)
なぜMODELの結果セットは2だけですか? –
WeekID = 1のため、EPOSのないモデル結果は1つしかないので(これは必要ありません)、WeekID = 4ではEPOSが0より大きい値を持っています。 –
@MartaLopes、私は溶液。 –