计算多列和

时间:2014-09-03 19:04:13

标签: sql sql-server

我有一个大表(除其他外)包括10个不同的细节和数量字段:

detail_1 | qty_1 | detail_2 | qty_2 | detail_3 | qty_3 | detail_4 | qty_4 | detail_5 | qty_5 | detail_6 | qty_6 |  ...etc

我尝试将每条记录的数量相加,然后计算共享共享总数的记录数。我使用以下声明设法实现了这一目标:

SELECT a.Total as [Quantity], COUNT(a.Total) as [Total]
FROM

(SELECT (ISNULL(qty_1, 0) 
       + ISNULL(qty_2, 0) 
       + ISNULL(qty_3, 0) 
       + ISNULL(qty_4, 0) 
       + ISNULL(qty_5, 0) 
       + ISNULL(qty_6, 0) 
       + ISNULL(qty_7, 0) 
       + ISNULL(qty_8, 0) 
       + ISNULL(qty_9, 0) 
       + ISNULL(qty_10, 0)) as [Total]                  
FROM endicia_temp) a

GROUP BY a.Total
ORDER BY Quantity

这给了我想要的输出:

Quantity Total
2        169    //169 records with total quantity 2
13       2      //2 records with total quantity 13
16       39
17       1
55       2
107      1      //1 record with total quantity 107

我现在遇到的问题是我需要添加一个where子句,以便每个记录中只包含特定数量的总数。像WHERE [detail_column_here] LIKE '%sample%'这样的东西。我们认为一条记录可能仅包含qty_1(基于detail_1),另一条记录可能包括qty_3qty_4qty_5(基于detail_3detail_4detail_5)。也许我过分思考它,但我不知道如何实现这一目标。

1 个答案:

答案 0 :(得分:1)

那么,使用您拥有的表结构,唯一的选择是在总和的每个组件中都有一个CASE语句:

SELECT (CASE WHEN detail_1 LIKE '%sample%' THEN ISNULL(qty_1, 0) ELSE 0 END
       + CASE WHEN detail_2 LIKE '%sample%' THEN ISNULL(qty_2, 0)  ELSE 0 END
       + CASE WHEN detail_3 LIKE '%sample%' THEN ISNULL(qty_3, 0)  ELSE 0 END
       + CASE WHEN detail_4 LIKE '%sample%' THEN ISNULL(qty_4, 0)  ELSE 0 END
       + CASE WHEN detail_5 LIKE '%sample%' THEN ISNULL(qty_5, 0)  ELSE 0 END
       + CASE WHEN detail_6 LIKE '%sample%' THEN ISNULL(qty_6, 0)  ELSE 0 END
       + CASE WHEN detail_7 LIKE '%sample%' THEN ISNULL(qty_7, 0)  ELSE 0 END
       + CASE WHEN detail_8 LIKE '%sample%' THEN ISNULL(qty_8, 0)  ELSE 0 END
       + CASE WHEN detail_9 LIKE '%sample%' THEN ISNULL(qty_9, 0)  ELSE 0 END
       + CASE WHEN detail_10 LIKE '%sample%' THEN ISNULL(qty_10, 0) ELSE 0 END)

正如您可能已经知道的那样,规范化您的结构将大大简化此类查询。