4

我有一张桌子

ANSWERS 
   qId
   toggle_value

它记录了一个 HTML 单选按钮值{Yes, N/A, No, Resolved}

现在我想计算和总结按问题 ID 分组的是、否、nas 和已解决的数量。

为简单起见,我开始构建每个单独的查询。

SELECT qId, count(*) as yes_qty FROM ANSWERS WHERE TOGGLE_VALUE='Yes' GROUP BY qId;
SELECT qId, count(*) as na_qty FROM ANSWERS WHERE TOGGLE_VALUE='NA' GROUP BY qId;
SELECT qId, count(*) as no_qty FROM ANSWERS WHERE TOGGLE_VALUE='No' GROUP BY qId;
SELECT qId, count(*) as resolved_qty FROM ANSWERS WHERE TOGGLE_VALUE='Resolved' GROUP BY qId;

但我真的希望它在一个查询中,所以我可以遍历列表并显示类似的内容(聚合 14 个清单和 3 个问题)

Q      Yes      No     NA     Resolved
1       4       10     0        10
2      14        0     0         0
3       7        0     7         0

我实际上并没有使用字符串作为切换值,而是使用数字 1=yes、2=NA 等...并且想知道是否会有更好的表格设计

ANSWERS 
   qId
   yes_value
   no_value
   na_value
   resolved_value

如果我更改表设计,我将不得不重构很多其他的东西,所以我希望让一个查询工作。

4

2 回答 2

5
SELECT qId,
       SUM(CASE WHEN TOGGLE_VALUE='Yes' THEN 1 ELSE 0 END) AS YesQty,
       SUM(CASE WHEN TOGGLE_VALUE='No' THEN 1 ELSE 0 END) AS NoQty,
       SUM(CASE WHEN TOGGLE_VALUE='NA' THEN 1 ELSE 0 END) AS NAQty,
       SUM(CASE WHEN TOGGLE_VALUE='Resolved' THEN 1 ELSE 0 END) AS ResolvedQty
  FROM ANSWERS 
 GROUP BY qId
于 2012-09-07T17:10:08.850 回答
1

我喜欢你的桌子设计。我会亲自用SUMandGROUP BY和 usingCASE子句来创建新列来解决这个问题。

于 2012-09-07T17:11:35.910 回答