我编写了一个返回下表的SQL查询,该表有3列。每个值都是一个百分比。
A列-B栏-C列
.1 .6 .3
如何旋转此表以便我有两列和三行:一列用于名称,第二列用于值?我希望结果看起来像
列-A。
专栏-B
专栏-C.3
以下是我使用的查询:
SELECT percent(SUM (CASE WHEN fups.status = 'complete' THEN 1 ELSE 0 END),
COUNT(fups.*)) AS "Column A",
percent(SUM (CASE WHEN fups.status = 'open' THEN 1 ELSE 0 END),
COUNT(fups.*)) AS "Column B",
percent(SUM (CASE WHEN fups.status = 'dismissed' THEN 1 ELSE 0 END),
COUNT(fups.*)) AS "Column C"
FROM (
SELECT *
FROM tasks
WHERE task_type = 'new'
) fups
答案 0 :(得分:0)
使用案例生成名称部分,然后按其分组并使用计数:
SELECT
CASE status
WHEN 'complete' THEN 'Column A'
WHEN 'open' THEN 'Column B'
WHEN 'dismissed' THEN 'Column C'
END name,
percent(COUNT(*), (SELECT COUNT(*) FROM tasks
WHERE task_type = 'new'
AND status IN ('completed', 'open', 'dismissed')) "percent"
FROM tasks
WHERE task_type = 'new'
AND status IN ('completed', 'open', 'dismissed')
GROUP BY CASE status
WHEN 'complete' THEN 'Column A'
WHEN 'open' THEN 'Column B'
WHEN 'dismissed' THEN 'Column C'
END
虽然为什么你不会简单地使用状态列的值来逃避我。
此外,如果您可以指出您正在使用的确切数据库,则可以采用更有效的方式对其进行编码。