SQL Server - 用于检索列名和列总和的查询

时间:2017-09-26 19:33:21

标签: sql sql-server tsql

查询有困难。我有一个名为带有大量列的产品的表,如下所示:

 X  |  Y  |  Z  | ... (and on)
----+-----+-----+
 4  |  9  |  4  |
 5  |  2  |  6  |
 2  |  5  |  9  |

然后我想开发一个查询,输出列名及其总和,如下所示:

ProductName  |  Quantity
-------------+-----------
    X        |     11
    Y        |     16
    Z        |     19
...

有什么想法吗?

提前致谢

3 个答案:

答案 0 :(得分:4)

当然,UNPIVOT和动态SQL可能性能更高,但以下内容将“动态”取消和汇总您的数据。

请注意,这会将行转换为XML,并且将排除NULL值

示例

       // some proces to get paths of files in the list sfiles
       double fraction = 0.0;
       this.progress_bar.set_fraction (fraction);
       int processed_files = 0;
       foreach (string sfile in sfiles) {
            do_some_proces_to_file(sfile);
            processed_files += 1;
            fraction = (double)processed_files/(double)sfiles.length;
            this.progress_bar.set_fraction (fraction);
            stdout.printf("Real fraction: %f\n", this.progress_bar.get_fraction());
        }

<强>返回

Select ProductName = C.Field
      ,Quanity     = sum(C.Value)
 From  YourTable A
 Cross Apply ( values (cast((Select A.* for XML RAW) as xml))) B(XMLData)
 Cross Apply (
                Select Field = a.value('local-name(.)','varchar(100)')
                      ,Value = a.value('.','int')           --<< Change to desired data type
                 From  B.XMLData.nodes('/row')  as C1(n)
                 Cross Apply C1.n.nodes('./@*') as C2(a)
                 Where a.value('local-name(.)','varchar(100)') not in ('FieldsTo','Exclude')
             ) C
 Group By C.Field

如果它有助于可视化,子查询会生成:

enter image description here

答案 1 :(得分:0)

假设您的表名为@junit.framework.Test,您可以使用UNPIVOT

yourtbl

答案 2 :(得分:0)

您可以将unpivotSUM一起使用,以达到预期效果。要为如此大量的属性创建SQL,我肯定会使用动态T-SQL。

SELECT ProductName, Quantity
FROM (
   SELECT SUM(X) x, SUM(y) y, SUM(z) z FROM your_table
)
UNPIVOT
( 
   Quantity FOR ProductName IN (X, Y, Z)
) AS t