使用SQL / Access创建一个类似于pivot的表输出

时间:2015-07-08 10:04:01

标签: mysql sql ms-access

我有一个由2列组成的表:

Tested_Object | Result

     A        |  OK
     A        |  NOT OK
     A        |  NOT OK
     B        |  OK

我需要有如下输出:

Tested_Object | SUM    | OK    | NOT_OK

     A        |  3     |1      | 2 
     B        |  1     |1      | 0 (or empty)

我尝试使用:

SELECT
t1.Tested_Object,
Count(t1.Result) AS SUM,
Count(t2.Result) AS OK,
Count(t3.Result) AS NOT_OK
FROM
(t1 LEFT JOIN (t1 AS t2) ON t1.Tested_Object=t2.Tested_Object) 
LEFT JOIN (t1 AS t3) WHERE t1.Tested_Object=t3.Tested_Object 

GROUP BY t1.Tested_Object

现在,如果我把:

WHERE (t2.Result="OK" AND t3.Result="NOT_OK")

WHERE (t2.Result="OK" OR t3.Result="NOT_OK")

t1 LEFT JOIN (t1 AS t2 WHERE t2.Result="OK") ON t1.Tested_Object=t2.Tested_Object

我为每列或错误获得相同的计数。

我设法得到不同的列号,只保存表中的所有OK,手动另一个表中的NOT OK。但我需要一个查询,从输入到输出表完全自动完成计算。

如果不清楚,我是一个新手用SQL :) 提前致谢

2 个答案:

答案 0 :(得分:1)

MySQL解决方案

您可以使用CASE ... WHEN ... THENOK值与NOT OK值区分开来。

SELECT Tested_Object
     , COUNT( Tested_Object ) AS `SUM`
     , SUM( CASE WHEN Result = 'OK' THEN 1 ELSE 0 END ) AS `OK`
     , SUM( CASE WHEN Result = 'NOT OK' THEN 1 ELSE 0 END ) AS `NOT_OK`
  FROM t1
 GROUP BY Tested_Object

MS Access解决方案

您可以使用IIF Function

SELECT Tested_Object
     , COUNT( Tested_Object ) AS SUM
     , SUM( IIF( Result = 'OK', 1, 0 ) ) AS OK
     , SUM( IIF( Result = 'NOT OK', 1, 0 ) ) AS NOT_OK
  FROM t1
 GROUP BY Tested_Object

答案 1 :(得分:0)

SELECT Tested_Object
 , count(*) SUM
 ,  Count(CASE
           WHEN Result = 'OK' THEN 1
         END) OK
 ,Count(CASE
           WHEN Result = 'NOT_OK' THEN 1
         END) NOTOK
FROM my_table 
GROUP 
BY Tested_Object;

在小提琴中找到解决方案http://sqlfiddle.com/#!6/22986/1