简体   繁体   English

如何在 SQL 中添加一列并在单个查询中同时基于其他列设置其值?

[英]How can i add a column in SQL and set its values based on other columns at the same time in a single query?

For example, I have a Student table with columns named: id , name , marks_obtained , total_marks , etc.例如,我有一个Student表,其中的列名为: idnamemarks_obtainedtotal_marks等。

I want to add a column named percentage whose values will be equal to ( marks_obtained / total_marks )*100.我想添加一个名为percentage的列,其值将等于( marks_obtained / total_marks )*100。

How can I do the whole thing in a single query?如何在单个查询中完成整个事情?

In Oracle 11g (since this is tagged Oracle) you can use a virtual column:在 Oracle 11g 中(因为它被标记为 Oracle),您可以使用虚拟列:

SQL Fiddle SQL小提琴

Oracle 11g R2 Schema Setup : Oracle 11g R2 架构设置

CREATE TABLE Student ( id, name, marks_obtained, total_marks ) AS
          SELECT 1, 'Alice',  90, 100 FROM DUAL
UNION ALL SELECT 2, 'Bob',    72, 100 FROM DUAL
UNION ALL SELECT 3, 'Claire', 93, 105 FROM DUAL;

ALTER TABLE Student ADD (
  percentage NUMBER GENERATED ALWAYS AS ( marks_obtained * 100 / total_marks ) VIRTUAL
);

Query 1 :查询 1

SELECT * FROM Student

Results :结果

| ID |   NAME | MARKS_OBTAINED | TOTAL_MARKS |        PERCENTAGE |
|----|--------|----------------|-------------|-------------------|
|  1 |  Alice |             90 |         100 |                90 |
|  2 |    Bob |             72 |         100 |                72 |
|  3 | Claire |             93 |         105 | 88.57142857142857 |

If you don't want to add a computed column to the table you can do the calculation in the SQL which fetches your data, eg:如果您不想在表中添加计算列,您可以在获取数据的 SQL 中进行计算,例如:

SELECT id,
       name,
       marks_obtained,
       total_marks,
       (marks_obtained / total_marks) * 100 AS PERCENTAGE
  FROM STUDENT

SQLFiddle here SQLFiddle在这里

Best of luck.祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM