GROUP BY or COUNT Like Field Values - UNPIVOT?

前端 未结 4 1232
一向
一向 2021-02-11 07:15

I have a table with test fields, Example

id         | test1    | test2    | test3    | test4    | test5
+----------+----------+----------+----------+----------+-         


        
4条回答
  •  逝去的感伤
    2021-02-11 07:38

    You could use an auxiliary on-the-fly table to turn columns into rows, then you would be able to apply aggregate functions, something like this:

    SELECT
      SUM(fields = 'P') AS passed,
      SUM(fields = 'F') AS failed,
      SUM(fields = 'I') AS incomplete
    FROM (
      SELECT
        t.id,
        CASE x.idx
          WHEN 1 THEN t.test1
          WHEN 2 THEN t.test2
          WHEN 3 THEN t.test3
          WHEN 4 THEN t.test4
          WHEN 5 THEN t.test5
        END AS fields
      FROM atable t
        CROSS JOIN (
          SELECT 1 AS idx
          UNION ALL SELECT 2
          UNION ALL SELECT 3
          UNION ALL SELECT 4
          UNION ALL SELECT 5
        ) x
      WHERE t.id = 12345
    ) s
    

提交回复
热议问题