3

这是我的观点,它给出了如上所述的输出:

CREATE
  ALGORITHM=UNDEFINED
  DEFINER=`root`@`localhost`
  SQL SECURITY DEFINER
VIEW new_view AS
  SELECT 'pcount'    AS ind_type,
         SUM(pcount) AS Index_val
  FROM   temp
UNION
  SELECT 'ncount',
         SUM(ncount)
  FROM   temp
;

结果:

+----------+------------+
| ind_type | 索引值 |
+----------+------------+
| 个数 | 76 |
| ncount | 第434章
+----------+------------+

现在我创建了另一个键,pcountncount使用MAX()

CREATE
  ALGORITHM=UNDEFINED
  DEFINER=`root`@`localhost`
  SQL SECURITY DEFINER
VIEW view_name AS
  SELECT pcount,
         ncount
  FROM   temp
  WHERE  id = (SELECT MAX(id) FROM temp)
;

给出结果:

+--------+--------+
| 个数 | ncount |
+--------+--------+
| 56 | 56 |
+--------+--------+

这个结果怎么可以看成上面的呢?

结果根据斯蒂芬的回答:

+----------+-----------+
| ind_type | Index_val |
+----------+-----------+
|        0 |         0 |
+----------+-----------+
1 row in set (0.01 sec)
4

2 回答 2

1

你可以试试这个:

CREATE VIEW test.t1 AS (
    SELECT 
        'pcount' AS type,
        `temp`.`pcount` AS value 
    FROM 
        `temp` 
    WHERE (
        `temp`.`id` = (
                SELECT 
                    MAX(`temp`.`id`) 
                FROM 
                    `temp`
        )
    )
    UNION 
    SELECT 
        'ncount' AS type,
        `temp`.`ncount` AS value 
    FROM 
        `temp` 
    WHERE (
        `temp`.`id` = (
                SELECT 
                    MAX(`temp`.`id`) 
                FROM 
                    `temp`
        )
    )
)
于 2013-09-17T07:52:41.753 回答
1

您可以在第二个示例中使用由两行组成的虚拟表(根据您要取消透视的列数)来取消透视查询的结果。以下是它的外观:

SELECT t.ind_type,
       CASE t.ind_type
         WHEN 'pcount' THEN v.pcount
         ELSE               v.ncount
       END AS Index_val
FROM   temp AS v
CROSS
JOIN   (
       SELECT 'pcount' AS ind_type
       UNION ALL
       SELECT 'ncount'
       ) AS t
WHERE  v.id = (SELECT MAX(id) FROM temp)
于 2013-09-19T07:14:47.157 回答