2015-01-13 29 views
1

我正在使用SQL Server 2014,我需要一些硬查詢的幫助。計數不同的多列模式

我有下表(MyTable)。這些列名稱僅用於示例。它們實際上完全不同。

id int, 
col1 int, 
col2 int, 
.. 
.. 
.. 
col70 int 

對於順序列的每對{(COL1,COL2),(col2_col3)...(col69_col70)},我需要計算以下內容:不同對每個值具有數 - col_i是靜態列,col_i + 1是另一列。每個值需要除以表中的記錄總量。例如:

col1 | col2 
45 | 789 
56 | 345 
99 | 234 
45 | 789 
45 | 222 
89 | 678 
89 | 345 
45 | 789 
90 | 234 
12 | 567 

計算:

((45, 789)+(45, 222))/10 
(56, 345)/10 
(99, 234)/10 
(45, 789)+(45, 222)/10 
(45, 789)+(45, 222)/10 
(89, 678)+(89, 345)/10 
(89, 678)+(89, 345)/10 
((45, 789)+(45, 222))/10 
(90, 234)/10 
(12, 567)/10 

輸出:

col1_col2 
    0.2 
    0.1 
    0.1 
    0.2 
    0.2 
    0.2 
    0.2 
    0.2 
    0.1 
    0.1 

解釋第一記錄: 45是靜態列的值,所以現在我會檢查col2有多少種不同的組合可供選擇:

45 | 789 
45 | 789 
45 | 222 
45 | 789 

總的不同組合除以表中的記錄數:2/10 = 0.2

此計算需要每對連續列。任何建議?是否有一個智能的方法來自動計算它,而不是每行都寫一行查詢?

+0

創建功能,然後在查詢中使用? – HaveNoDisplayName

+0

爲什麼你使用這麼多類似的數據領域?看起來像一個有缺陷的模型。 –

+0

@GoatCO這就是我從客戶端獲取數據的方式。我無法改變結構。 – Omri

回答

0

一個例子假設你有一個主鍵:

create table my_table 
(column_id int not null, 
column1 int not null, 
column2 int not null); 

insert into my_table 
(column_id, column1, column2) 
values 
(1, 45,789), 
(2, 56,345), 
(3, 99,234), 
(4, 45,789), 
(5, 45,222), 
(6, 89,678), 
(7, 89,345), 
(8, 45,789), 
(9, 90,234), 
(10, 12,567); 

declare @column_a as nvarchar(100) = N'column1'; 
declare @column_b as nvarchar(100) = N'column2'; 
declare @result_column as nvarchar(100) = N'column1_2'; 
declare @sql_string as nvarchar(4000) 

set @sql_string = 
'select a.column_id, 
1.0 * count(distinct b.' + @column_b + ')/(count(a.' + @column_a + ') over()) as ' + @result_column 
+ ' from my_table a 
inner join my_table b 
on a.' + @column_a + ' = b.' + @column_a + 
' group by a.column_id, a.' + @column_a + 
' order by a.column_id'; 

-- print @sql_string; 
execute(@sql_string); 

如果有,你可以使用ROWNUMBER()函數來創建一個標識符的主鍵,但結果順序會改變。 print命令對於檢查動態sql字符串非常有用,在這裏註釋掉了。

把動態SQL到一個存儲過程:

​​