我有一个包含3列的表格,例如Food
,Type
和Taste
。
Food
可以有任何内容Type
可能有'Fruit'或'Vegetable'作为可能的值Taste
可能包含'Bad','Good'或'Delicious'作为可能的值我试图得到(到目前为止没有运气)一个SQL语句,它会产生一个像:
这样的表 Bad Good Delicious Total
Fruit 05 09 16 20
Vegetables 12 20 03 35
Total 17 29 19 55
输出表上的数字是每个Food
/ Type
组合表格中Taste
个数的COUNT。
如何实现?
答案 0 :(得分:1)
前两行可以在一个带有子查询子句的查询中完成:
SELECT X."Type",
SUM(X."Bad") AS "Bad",
SUM(X."Good") AS "Good",
SUM(X."Delicious") AS "Delicious",
SUM(X."Total") AS "Total"
FROM (SELECT "Type",
CASEWHEN("Taste" = 'Bad',1,0) AS "Bad",
CASEWHEN("Taste" = 'Good',1,0) AS "Good",
CASEWHEN("Taste" = 'Delicious',1,0) AS "Delicious",
1 AS "Total" FROM "YourTableName") X
GROUP BY "Type"
子查询创建列" Bad"," Good"和#34;美味"如果每列中有1或0,则查询的外部会将所有值相加。
要获取底部的总计行,您必须使用Base解析器不支持的UNION ALL
。要使此查询生效,您需要启用Edit
→Run SQL Directly
选项。 (这将禁用某些需要解析器的表单和报表功能 - 它可能对您的使用无关紧要,但如果您稍后在表单或报表中使用此查询,则仅供参考。)
您UNION ALL
的查询基本上是相同的查询,您只是不按类型分组。所以总计:
SELECT X."Type",
SUM(X."Bad") AS "Bad",
SUM(X."Good") AS "Good",
SUM(X."Delicious") AS "Delicious",
SUM(X."Total") AS "Total"
FROM (SELECT "Type",
CASEWHEN("Taste" = 'Bad',1,0) AS "Bad",
CASEWHEN("Taste" = 'Good',1,0) AS "Good",
CASEWHEN("Taste" = 'Delicious',1,0) AS "Delicious",
1 AS "Total" FROM "YourTableName") X
GROUP BY "Type"
UNION ALL
SELECT 'Total' AS "BottomTotal",
SUM(Y."Bad"),
SUM(Y."Good"),
SUM(Y."Delicious"),
SUM(Y."Total")
FROM (SELECT CASEWHEN("Taste" = 'Bad',1,0) AS "Bad",
CASEWHEN("Taste" = 'Good',1,0) AS "Good",
CASEWHEN("Taste" = 'Delicious',1,0) AS "Delicious",
1 AS "Total" FROM "YourTableName") Y
GROUP BY "BottomTotal"
确保替换" YourTableName"与您的实际表名一起。