必要なのはピボットクエリです。 MySQLにはそのためのステートメントがないため、「手動で」記述する必要があります(より正確には、動的SQL式を作成します):
したがって、次のようになります。
-- First you need to build the column list.
-- The "CASE ... END" expression will filter the data for each column
-- I use "max()" as an example; use whatever aggregate function you need.
select
group_concat(distinct
concat(
'max(case when del_ProductID = ', del_productID, ' then del_id end) ',
'as `del_productID-', del_productID, '` '
)
)
into @sql
from example;
-- Now build the full SELECT statement
set @sql = concat('SELECT del_date, ', @sql, ' from example group by del_date');
-- OPTIONAL: Check the SELECT statement you've just built
select @sql;
-- Prepare a statement using the SELECT statement built above
prepare stmt from @sql;
execute stmt;
-- When you are done, be sure to dealocate the prepared statement
deallocate prepare stmt;
説明
「おい、これはかなり複雑に見える!」と言うかもしれません...しかし、それはまったく複雑ではありません(それはただ面倒です)。では、上記のソリューションはどのように機能しますか?
最初のステップは、列リストとそれを埋めるための式を作成することです。group_concat() 関数は行の値(または式)を受け取り、それらをコンマで区切って連結します。ピボットテーブルの結果に値を表示するには、集計関数が必要です。 max()を選択しました 例として、sum()を使用できます 、average() またはその他の集計関数。
case ... end
集計関数内のピースでは、ピボットテーブルの各列がdel_productIDの値と一致する必要があります したがって、たとえば、case when del_ProductID = 1 then del_id end del_idの値を返します del_ProductIDの場合のみ は1です(nullを返します それ以外の場合は、else 0を追加できます たとえば、ゼロを返したい場合)。
select ... into
式の結果を@sqlという変数に格納します 。
列リストを作成したら、残りのselectを記述する必要があります ステートメント...これはconcat()で行われます 機能。
残りの部分については、非常に簡単です:@sql は文字列であるため、実行する場合は、その値(select)を使用してプリペアドステートメントを作成する必要があります。 ステートメント)、それを実行します。