0

我有以下查询效果很好,但我想知道我是否可以更改 Pivot 结果。

这是当前输出的示例:

SERIAL_ID  Test_1  Test_2  Test_3  Test_4  Test_5    Test_6
12398701   NULL    NULL    NULL    NULL    Memory_1  NULL

这是我想要的输出。如果 TEST_AREA 为 NULL 并且没有 TEST_RESULT = PASS 或 FAIL(无记录)显示 INC。并且,如果 TEST_RESULT = PASS 将 NULL 替换为 PASS。下面的示例 Test_3 和 Test_6 没有运行(没有记录)

SERIAL_ID  Test_1  Test_2  Test_3  Test_4  Test_5    Test_6
12398701   PASS    PASS    INC     PASS    Memory_1  INC

这是我需要修改的查询:

select SERIAL_ID, Test_1, Test_2, Test_3, Test_4, Test_5, Test_6
from
(
  select SERIAL_ID, FAIL_CODE, TEST_AREA
  from
  (
    select f1.SERIAL_ID, f1.FAIL_CODE, f1.TEST_AREA, f1.TEST_RESULT,
      row_number() over(partition by f1.SERIAL_ID, f1.TEST_AREA
                        order by f1.TEST_DATE desc) seq
    from dbo_TBL_DM_TEST_RESULTS_Flex f1
    where f1.TEST_DATE> '2013-07-01' 
  ) d
  where seq = 1
    and (TEST_RESULT='fail' or TEST_RESULT='Pass') 
) d
pivot
(
    max(FAIL_CODE)
    for TEST_AREA in (Test_1, Test_2, Test_3, Test_4, Test_5, Test_6)
) piv;

以下是数据示例:

TEST_AREA TEST_DATE              SERIAL_ID  TEST_RESULT  FAIL_CODE
Test_1    8/14/2013 11:29:24 AM  12398701   PASS         NULL
Test_2    8/17/2013 08:49:35 AM  12398701   PASS         NULL
Test_2    8/17/2013 10:15:38 PM  12398701   PASS         NULL
Test_4    8/17/2013 10:23:22 PM  12398701   FAIL         Pwr_up
Test_4    8/17/2013 10:24:22 PM  12398701   PASS         NULL
Test_5    8/18/2013 07:30:19 AM  12398701   FAIL         Pwr_up
Test_5    8/18/2013 07:34:34 AM  12398701   FAIL         Memory_1
4

1 回答 1

0

这取决于您的测试结果/失败代码是 Pass、Null 还是 Fail、Not Null。这有点蛮力,但是您在枢轴内可以做的事情受到限制:

select 
  serial_id, 
  IsNull(Test_1, 'INC') Test_1, 
  IsNull(Test_2, 'INC') Test_2,
  IsNull(Test_3, 'INC') Test_3,
  IsNull(Test_4, 'INC') Test_4,
  IsNull(Test_5, 'INC') Test_5,
  IsNull(Test_6, 'INC') Test_6
from (
  select
    serial_id,
    IsNull(fail_code, test_result) fail_code, -- propagate 'Pass' up
    test_area
  from (
    select
      f1.serial_id,
      f1.fail_code,
      f1.test_area,
      f1.test_result,
      row_number() over (
        partition by 
          f1.serial_id,
          f1.test_area
        order by
           f1.test_date desc
      ) seq
    from 
      dbo_tbl_dm_test_results_flex f1
    where
      f1.test_date > '2013-07-01' 
    ) d
  where 
    seq = 1 and 
    test_result in ('fail', 'Pass') 
  ) d
pivot (
    max(fail_code)
    for test_area in (Test_1, Test_2, Test_3, Test_4, Test_5, Test_6)
) piv;

Example Fiddle

于 2013-09-26T22:52:08.090 回答