簡體   English   中英

在SQL Server中將一個表中的列名與另一表中的列數據進行比較

[英]Comparing Column Name in one Table with Column Data in another table in SQL Server

我正在嘗試將tblFactorDefinition作為列值一部分存在的列名與tblConstituent實際值與匹配的列名進行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'

任何幫助贊賞嗎?

謝謝。

您可以使用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 <>小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM