LibreOffice Base - SQL查询的困难

时间:2016-03-21 22:09:07

标签: sql libreoffice base

我有一个包含3列的表格,例如FoodTypeTaste

  • 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。

如何实现?

1 个答案:

答案 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。要使此查询生效,您需要启用EditRun 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"与您的实际表名一起。