まず-------------そして、あなただけの古いテーブル構造を持っている場合にはUNPIVOTを使用してデータを、新しい変換テーブル構造
CREATE TABLE ParentTable
(
Germany decimal(16,2),
France decimal(16,2)
)
INSERT INTO ParentTable VALUES(100,2000)
CREATE TABLE CompareTable
(
India decimal(16,2),
Korea decimal(16,2)
)
INSERT INTO CompareTable VALUES(100,5000)
にデータを挿入します----------- NEWテーブルの構造の場合にDYMANIC列名を持つUNPIVOTを使用した
CREATE TABLE ParentTable_NEW
(
Country varchar(100),
TradeValue decimal(16,2)
)
CREATE TABLE CompareTable_NEW
(
Country varchar(100),
TradeValue decimal(16,2)
)
-------------------- YOUその他の国を追加することがあります。親のテーブル
declare @cols nvarchar(max)
select @cols = coalesce(@cols+N',', N'') + quotename(c.name) from syscolumns c
inner join sysobjects o on c.id = o.id and o.xtype = 'u'
where o.name = 'ParentTable' -- order by c.colid
declare @query nvarchar(max)
select @query = N'
select Country,Value
from
(
select ' + @cols + '
from ParentTable
) as cp
unpivot
(
Value for Country in (' + @cols + ')
) as up
'
INSERT INTO ParentTable_NEW
exec sp_executesql @query
私は私の質問を編集した@derloopkatあなたがより多くの国を追加することができた場合のDYMANIC列名を持つUNPIVOTを使用した
--------------------はTABLE
declare @cols2 nvarchar(max)
select @cols2 = coalesce(@cols2+N',', N'') + quotename(c.name) from syscolumns c
inner join sysobjects o on c.id = o.id and o.xtype = 'u'
where o.name = 'CompareTable' -- order by c.colid
declare @query2 nvarchar(max)
select @query2 = N'
select Country,Value
from
(
select ' + @cols2 + '
from CompareTable
) as cp
unpivot
(
Value for Country in (' + @cols2 + ')
) as up
'
INSERT INTO CompareTable_NEW
exec sp_executesql @query2
----------Final query
SELECT part.Country AS partner_country,
part.TradeValue AS parter_value,
comp.Country AS comp_country,
comp.TradeValue AS comp_value,
CASE WHEN part.TradeValue > comp.TradeValue THEN 1 ELSE 0 END AS 'Status'
FROM ParentTable_NEW part
CROSS APPLY CompareTable_NEW comp
ORDER BY part.Country
を比較します。 –
あなたのコードには何が問題なのですか? –
テーブルの定義が間違っていると思います。国は列ではなく行であってはなりません。これは、テーブルの列スキーマを取得し、クエリで使用するよう強制します。典型的には、単純なクエリがより複雑なものになる理由です。 – derloopkat