2015-11-06 69 views
0

您可以請幫助這個,我試圖編寫一個查詢從列數組中檢索總量,我不知道是否有辦法做到這一點,我檢索列的陣列我從這個查詢需要:如何使用SQL Server 2008上的列數組進行查詢

USE Facebook_Global 
GO 

SELECT c.name AS column_name 
FROM sys.tables AS t 
INNER JOIN sys.columns AS c 
    ON t.OBJECT_ID = c.OBJECT_ID 
WHERE t.name LIKE '%Lifetime Likes by Gender and###$%' and c.name like '%m%' 

這給了我這個表

column_name 
M#13-17 
M#18-24 
M#25-34 
M#35-44 
M#45-54 
M#55-64 
M#65+ 

所以我需要一個查詢,讓我在表中列出的那些列的總金額。這可能嗎?

我只想澄清一點:

我有這個表


Date F#13-17 F#18-24 F#25-34 F#35-44 F#45-54 F#55-64 F#65+ M#13-17 M#18-24 M#25-34 M#35-44 M#45-54 M#55-64 M#65+ 
2015-09-06 00:00:00.000 257 3303 1871 572 235 116 71 128 1420 824 251 62 32 30 
2015-09-07 00:00:00.000 257 3302 1876 571 234 116 72 128 1419 827 251 62 32 30 
2015-09-08 00:00:00.000 257 3304 1877 572 234 116 73 128 1421 825 253 62 32 30 
2015-09-09 00:00:00.000 257 3314 1891 575 236 120 73 128 1438 828 254 62 33 30 
2015-09-10 00:00:00.000 259 3329 1912 584 245 131 76 128 1460 847 259 66 37 31 
2015-09-11 00:00:00.000 259 3358 1930 605 248 136 79 128 1475 856 261 67 39 31 
2015-09-12 00:00:00.000 259 3397 1953 621 255 139 79 128 1486 864 264 68 41 31 
2015-09-13 00:00:00.000 259 3426 1984 642 257 144 80 129 1499 883 277 74 42 32 

而且我需要的所有列包含單詞F和其他containig一個SUM列字M,而不是使用這樣的東西: F#13-17 + F#18-24 + F#25-34 + F#35-44 + F#45-54 +等。

這可能嗎?

+0

是的,當然是可以的。你將不得不創建一個動態查詢並執行它。存儲過程是我如何去做的。下面是一個[使用動態SQL的存儲過程示例](http://www.sqlteam.com/article/using-dynamic-sql-in-stored-procedures)。 – zedfoxus

回答

1

嘗試這樣:

with derivedTable as 
(sql from your question goes here) 
select column_name 
from derivedTable 
union 
select cast(count(*) as varchar (10) + 'records' 
from derivedTable 
+0

謝謝你的回答丹,我剛剛編輯了我的問題,因爲我認爲我不太清楚。 – dasg7