【问题标题】:How to use CASE statement to update data (as fractions) in the table?如何使用 CASE 语句更新表中的数据(作为分数)?
【发布时间】:2021-12-27 06:12:37
【问题描述】:

查询表:

Different Fruits Total Fruits Fruits Fraction
3 5
2 6
2 2
4 6
1 1
6 6
6 16
4 20

更新表:

Different Fruits Total Fruits Fruits Fraction
3 5 3/5
2 6 2/6
2 2 2/2
4 6 4/6
1 1 1/1
6 6 6/6
6 16 6/6
4 20 4/6

共有 6 种不同的水果。但是,每条记录的总果实数可以大于 6。

我想使用这样的 case 语句:

WHEN Total Fruits < 6 THEN Fruits Fraction = Different Fruits/Total Fruits
ELSE Fruits Fraction = Different Fruits/6
    

我不想简化分数,可能我认为它会使用字符数据类型。

请帮忙。

提前致谢。

【问题讨论】:

    标签: sql sqlite


    【解决方案1】:

    你可以试试这个:

    SELECT "different fruits", "total fruits", 
      CASE 
        WHEN "total fruits" > 6 THEN "different fruits"||'/'||'6'
        ELSE "different fruits"||'/'||"total fruits"
        END AS fruits_fraction
    FROM your_table
    

    dbfiddle 链接here

    【讨论】:

      【解决方案2】:

      不需要CASE 表达式。
      您可以使用MIN() scalar function:

      SELECT DifferentFruits, TotalFruits,
             DifferentFruits || '/' || MIN(TotalFruits, 6) FruitsFraction
      FROM tablename;
      

      或者,如果你想更新表格:

      UPDATE tablename
      SET FruitsFraction = DifferentFruits || '/' || MIN(TotalFruits, 6);
      

      请参阅demo。

      【讨论】:

        猜你喜欢
        • 2022-01-19
        • 2017-02-28
        • 1970-01-01
        • 1970-01-01
        • 2014-01-06
        • 1970-01-01
        • 2020-02-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多