SQL Server Calculate table score based on column combination

jobtbby3  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(98)

I wish to build a query to calculate the table score based on a column combination in the table.

So, I have table 'A' that contains database metadata.
| DE_Type | Column_Name | Table_Name | Data_System_Instance | Database_Name | Data_Element_Counts |
| ------------ | ------------ | ------------ | ------------ | ------------ | ------------ |
| Name | SalesName | tbl_sales | DB_PROD | Daily_Sales | 40 |
| Govt_ID | SSN | tbl_sales | DB_PROD | Daily_Sales | 40 |
| Name | CustName | tbl_customer | DB_PROD | Daily_Customer | 5200 |
| Name | PIC | tbl_supplier | DB_PROD | Daily_Supplier | 21 |
| Email Address | Email | tbl_supplier | DB_PROD | Daily_Supplier | 21 |
| Phone Number | Handphone | tbl_supplier | DB_PROD | Daily_Supplier | 21 |

and table 'B' as a parameter table

IDDE_1DE_2Score
1NameGovt_ID3
2NamePassport3
3NameEmail Address2
4NamePhone Number2
5Govt_IDEmail Address1.5

I am imagining will have an output like this:

Table_NameData_Element_CountsDE_Score
tbl_sales403
tbl_supplier214
tbl_customer52001

Table_Name is obtained from Table 'A' Table_Name; Data_Element_Counts is obtained from Table 'A' Data_Element_Count; DE_Score is the hardest part, it needs to gather all DE_type from single table, then lookup to table 'B', to find whether the collected columns have a combination like in table 'B' (DE_1 & DE-2)

So, how can I develop a query to have an output like this?

wf82jlnq

wf82jlnq1#

As you did not explain how the DE_1 - DE_2 comes about, I assumed, you need to use all possible combination of DE_Type to match with the parameter table.

The first CTE finds the combination of DE_Type after that join to the parameter table to get the Score .

For the case of tbl_customers it will not have any match with the parameter table at all. And it handled separately and UNION with the matching result.

with 
combi as
(
  select t1.Table_Name, 
         t1.Data_Element_Counts, 
         DE_1 = t1.DE_Type, 
         DE_2 = t2.DE_Type
  from   meta t1
         inner join meta t2 on  t1.Table_Name = t2.Table_Name
                           and  t1.DE_Type   <> t2.DE_Type
),
final as
(  
  select c.Table_Name, 
         c.Data_Element_Counts, 
         DE_Score = sum(p.Score)
  from   combi c
         inner join para p on c.DE_1 = p.DE_1
                          and c.DE_2 = p.DE_2
  group by c.Table_Name, c.Data_Element_Counts
)
select Table_Name, Data_Element_Counts, DE_Score
from   final 
union all
select Table_Name, Data_Element_Counts, DE_Score = 1
from   meta m
where  not exists
       (
           select *
           from   final x
           where  x.Table_Name = m.Table_Name
       )

相关问题