2015-11-06 48 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