创建过滤条件:基于两个表

时间:2017-06-26 18:26:21

标签: sql sql-server-2012

有2个表PartnerCountry和ComparerCountry如下。

更新了表格结构

PartnerTable
Country                 TradeValue
---------------          -----------  
Germany                 |  100
France                  |  2000


ComparerTable   
Country                 TradeValue
---------------          -----------  
India                  |  100
Korea                  |  5000

旧表格结构

PartnerTable
Germany                France  
---------------        -----------  
100                 |  2000


ComparerTable   
India                 Korea  
---------------       -----------  
100                 |  5000 

需要条件

  case when  (    [Germany]>[India] 
                       or 
                 [Germany]>[Rep. of Korea] ) 

             or
         (
                 [france]>[India] 
                      or 
                  [france]>[Rep. of Korea]) then '1' else '0' end as 'Status'

该表可以包含更多国家/地区。合作伙伴表中任何国家/地区的值必须大于任何比较表。

如何根据新的表定义实现上述目标? 我打算编写动态查询来准备条件。

1 个答案:

答案 0 :(得分:1)

首先使用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)

------------------------新表结构

  CREATE TABLE ParentTable_NEW
    (
    Country varchar(100),
    TradeValue decimal(16,2)
    )


    CREATE TABLE CompareTable_NEW
    (
    Country varchar(100),
    TradeValue decimal(16,2)
    )

--------------------如果使用不明人名字的情人节,你可以添加更多国家的父母身份表

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 

--------------------如果使用不明飞机的名字,你可以添加更多国家比较表

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