在SQL Server中将一个表中的列名与另一表中的列数据进行比较

时间:2019-05-16 16:24:06

标签: sql tsql sql-server-2012

我正在尝试将tblFactorDefinition中作为列值一部分存在的列名与tblConstituent中的实际值匹配的列名进行比较,以查找这两个表之间的差异。

即使存在差异,我也无法获得预期的输出。我在下面发布了数据库模式和示例数据,并显示了预期的输出:

下面的三个表格是tblFactorDefinitiontblConstituenttblFamily

FamilyID | FieldName  |  FactorDefinition  |  PropertyTypeID
---------+------------+--------------------+----------------
10216    |  Factor1   |  901               |  300
10216    |  Factor2   |  901               |  305
10216    |  Factor3   |  901               |  310


ConstituentID | FamilyID |  ListingID | Factor1 | Factor2 | Factor3 | Factor9
--------------+----------+------------+---------+---------+---------+---------
1101          | 10216    |    1       |  0.1    | NULL    |  0.5    |   1.0
1105          | 10216    |    2       |  0.1    | 0.3     |  0.5    |   1.0
1108          | 10216    |    5       |  0.45   | 0.42    |  NULL   |   1.0


FamilyID | OpenDate
---------+------------
10216    | 2016-05-16

预期的输出如下所示:

FamilyID  |  FieldName   |  ConstituentID
----------+--------------+---------------
10216     |   Factor2    |  1101
10216     |   Factor3    |  1108

这是查询,我的逻辑不正确,因此什么也不返回。

SELECT
    T.FamilyID,
    C.COLUMN_NAME,
    T.ConstituentID
FROM 
    SolaDBServer..tblConstituent T
INNER JOIN 
    INFORMATION_SCHEMA.COLUMNS C ON T.FamilyID = C.COLUMN_NAME 
                                 AND C.TABLE_NAME = 'tblFactorDefinition'  
                                 AND T.FamilyID = 10216
LEFT OUTER JOIN 
    SolaDBServer..tblConstituent tc ON tc.FamilyID = T.FamilyID 
INNER JOIN 
    SolaDBServer..tblFamily tf ON tf.FamilyID = tc.FamilyID  
                               AND tf.OpenDate = CAST(GETDATE() AS DATE)
WHERE 
    C.COLUMN_NAME = 'FieldName'

对此有任何帮助吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用 UNPIVOT

请注意,我在查询中使用了 IIF 函数。 (您需要SQL Server 2012或更高版本)

如果您使用的是旧版本,请使用case语句替换它们。

尝试一下:

select a.FamilyID,a.FieldName,a.ConstituentID from 
(
select FamilyID,FieldName, ConstituentID, indicator
from 
(select c.ConstituentID,c.FamilyID
,iif(factor1 is null,1,0) as Factor1  --indicator for null
,iif(factor2 is null,1,0) as Factor2
,iif(factor3 is null,1,0) as Factor3
,iif(factor9 is null,1,0) as Factor9
from tblConstituent c
join tblFamily f
on f.FamilyID = c.FamilyID
where f.OpenDate = cast (getdate() as date)
)p
unpivot
(Indicator for FieldName
 in ([Factor1],[Factor2],[Factor3],[Factor9])
 ) as unpvt    
) a
join tblFactorDefinition b  --check if their factor(s) exist for specific ID
on a.FamilyID = b.FamilyID
and a.FieldName = b.FieldName 
where a.Indicator = 1

测试结果(我又添加了一个具有不同FamilyID的行):

DB<>Fiddle