Multifilter SQL Server Pivot Count Query to table

时间:2015-08-21 01:41:01

标签: sql-server pivot

我之前从未使用过SQL Pivot并需要帮助

我在MS SQL Server 2012中有以下数据表(wkYield),如下所示:

| id  | Trav_num | Part_num | Reason_code | Scrap |  date    |
| 1   | 123123   | 400      | cw_iweld    |  1    | 1/1/2015 |
| 2   | 123122   | 400      | cw_iweld    |  1    | 1/1/2015 |
| 3   | 123124   | 400      | cw_iweld    |  0    | 1/7/2015 |
| 4   | 123124   | 400      | cw_iweld    |  1    | 1/7/2015 |  
| 5   | 123121   | 400      | cw_hole     |  0    | 1/1/2015 |
| 6   | 123121   | 400      | cw_hole     |  1    | 1/1/2015 |
| 7   | 123110   | 400      | cw_hole     |  0    | 1/7/2015 |
| 8   | 123110   | 400      | cw_hole     |  1    | 1/7/2015 |
| 9   | 123111   | 410      | cw_iweld    |  0    | 1/1/2015 |
| 10  | 123111   | 410      | cw_iweld    |  1    | 1/1/2015 |
| 11  | 123333   | 410      | cw_iweld    |  1    | 1/1/2015 |

我想使用SQL来旋转数据来计算行数,并显示如下:

| Part_num | Reason_code | Week | Scrap=1 Cnt(reason)| Scrap=0 Cnt(reason)|
| 400      |  cw_weld    |  1   |       2            |     1              |
| 400      |  cw_hole    |  1   |       1            |     1              |
| 400      |  cw_weld    |  2   |       1            |     1              |
| 400      |  cw_hole    |  2   |       1            |     1              | 
| 410      |  cw_iweld   |  1   |       2            |     1              | 

然后结果应放在表wkYieldSum

我不知道任何给定的周数是什么原因代码(它们每周都会改变,但确实有很多重复。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

你可以用两种方式做到这一点conditional Aggregate另一种方式是Pivot。我更喜欢条件聚合,在我看来更具可读性

select Part_num,
       Reason_code,
       datepart(Week,[date]) as [Week],
       count(case when Scrap=1 then 1 end) as [Scrap=1 Cnt(reason)],
       count(case when Scrap=0 then 1 end) as [Scrap=0 Cnt(reason)],
From Yourtable
Group by Part_num,
         Reason_code,
         datepart(Week,[date])