当前位置:网站首页>100 important knowledge points that SQL must master: creating calculation fields
100 important knowledge points that SQL must master: creating calculation fields
2022-06-27 21:28:00 【Guge academic】
7.1 Calculated field
The data stored in the database table is generally not in the format required by the application , Here are some examples
Example .
The company name needs to be displayed , You also need to display the address of the company , But these two messages are stored in
In different table columns .
City 、 The state and zip code are stored in different columns ( It should be ), But the e-mail label is marked
The printer needs to retrieve them as a properly formatted field .
Column data is case mixed , But the report program needs to show all data in uppercase .
The item order table stores the price and quantity of the item , Don't store the total price of each item ( Price
Multiply the lattice by the quantity ). But for printing invoices , The total price of the goods needed .
It is necessary to make statistics according to the table data, such as total 、 Calculation of the average .
In each of the above examples , None of the data stored in the table is required by the application . We
You need to retrieve the transformation directly from the database 、 Calculated or formatted data , Instead of retrieving
Data , Then reformat it in the client application .
This is where calculated fields can come in handy . Different from the columns introduced in previous lessons , Calculation
The field does not actually exist in the database table . The calculation field is run at SELECT Statement within
Created .
Field (field)
Basically with columns (column) It means the same , Often used interchangeably , But database column one
Generally called column , The term field is usually used in the case of calculating fields .
Special attention required , Only the database knows SELECT Which columns in the statement are the actual table columns ,
Which columns are calculated fields . From the client ( Like an application ) Look at , Calculate the data of the field and
The data of other columns is returned in the same way .
Tips : Format of client and server
stay SQL Many of the transformations and formatting that can be done within a statement can be done directly on the client side
Within the application . But generally speaking , It is better to complete these operations on the database server than in
It is much faster to complete in the client .
7.2 Splicing field
To illustrate how to use calculated fields , Let's take a simple example , Create two columns
The title of the .
Vendors The table contains supplier name and address information . If you want to generate a supplier report , Need to be
To format the name ( Location ) List the supplier's location in .
This report requires a value , The data in the table is stored in two columns vend_name and vend_country
in . Besides , You need to use parentheses vend_country Cover up , These things are not stored
In the database table . This returns the name and address of the supplier SELECT The sentence is very simple , but
How do we create this composite value ?
Splicing (concatenate)
Join values together ( Append one value to another ) Form a single value .
The solution is to splice the two columns . stay SQL Medium SELECT In the sentence , One can be used
A special operator to splice two columns . According to what you use DBMS, This operator can be used
plus ( + ) Or two vertical bars ( || ) Express . stay MySQL and MariaDB in , You have to use
Special functions .
explain : yes + still || ?
SQL Server Use + Number .DB2、Oracle、PostgreSQL and SQLite Use || . detailed
Please refer to the specific DBMS file .
Here is an example of using the plus sign ( Most of the DBMS Use this grammar ):
Input ▼
SELECT vend_name + '(' + vend_country + ')'
FROM Vendors
ORDER BY vend_name;
Output ▼
-----------------------------------------------------------
Bear Emporium (USA )
Bears R Us (USA )
Doll House Inc. (USA )
Fun and Games (England )
Furball Inc. (USA )
Jouets et ours (France )
The following is the same statement , But it uses || grammar :
Input ▼
SELECT vend_name || '(' || vend_country || ')'
FROM Vendors
ORDER BY vend_name;
Output ▼
-----------------------------------------------------------
Bear Emporium (USA )
Bears R Us (USA )
Doll House Inc. (USA )
Fun and Games (England )
Furball Inc. (USA )
Jouets et ours (France )
Here's how to use MySQL or MariaDB The statements you need to use :
Input ▼
SELECT Concat(vend_name, ' (', vend_country, ')')
FROM Vendors
ORDER BY vend_name;
analysis ▼
The top two SELECT Statement to splice the following elements :
Stored in vend_name The names in the columns ;
A string containing a space and an open parenthesis ;
Stored in vend_country The countries in the list ;
A string containing a closing parenthesis .
From the above output, you can see , SELECT Statement returns a column containing the above four elements
( Calculated field ).
Look at the above SELECT The output returned by the statement . Two columns combined into one calculation field are used
Fill in the blanks . Many databases ( Not all ) Save text values filled with column widths , But actually
You don't need these spaces for the results you want . To return formatted data correctly , This must be removed
Some spaces . This can be used SQL Of RTRIM() Function to complete , As shown below :
Input ▼
SELECT RTRIM(vend_name) + ' (' + RTRIM(vend_country) + ')'
FROM Vendors
ORDER BY vend_name;
Output ▼
-----------------------------------------------------------
Bear Emporium (USA)
Bears R Us (USA)
Doll House Inc. (USA)
Fun and Games (England)
Furball Inc. (USA)
Jouets et ours (France)
The following is the same statement , But it uses || :
Input ▼
SELECT RTRIM(vend_name) || ' (' || RTRIM(vend_country) || ')'
FROM Vendors
ORDER BY vend_name;
Output ▼
-----------------------------------------------------------
Bear Emporium (USA)
Bears R Us (USA)
Doll House Inc. (USA)
Fun and Games (England)
Furball Inc. (USA)
Jouets et ours (France)
analysis ▼
RTRIM() Function to remove all spaces to the right of the value . By using RTRIM() , Each column goes into
All right, tidy up .
explain :TRIM function
majority DBMS All support RTRIM() ( As I just saw , It removes the right side of the string
Space )、 LTRIM() ( Remove the space to the left of the string ) as well as TRIM() ( Remove the characters
The spaces on the left and right of the string ).
Use the alias
As you can see from the previous output , SELECT Statement can splice address fields very well . however ,
What is the name of this new calculation column ? It doesn't actually have a name , It's just a value . Such as
Only in SQL Check the results in the query tool , There's nothing wrong with that . however , One
Unnamed columns cannot be used in client applications , Because the client has no way to reference it .
To solve this problem ,SQL Support column aliases . Alias (alias) Is a field or value
Alternate name . It's called AS Key words are given to . Please look at the following SELECT sentence :
Input ▼
SELECT RTRIM(vend_name) + ' (' + RTRIM(vend_country) + ')'
AS vend_title
FROM Vendors
ORDER BY vend_name;
Output ▼
vend_title
-----------------------------------------------------------
Bear Emporium (USA)
Bears R Us (USA)
Doll House Inc. (USA)
Fun and Games (England)
Furball Inc. (USA)
Jouets et ours (France)
The following is the same statement , But it uses || grammar :
Input ▼
SELECT RTRIM(vend_name) || ' (' || RTRIM(vend_country) || ')'
AS vend_title
FROM Vendors
ORDER BY vend_name;
Here is MySQL and MariaDB Statements used in :
Input ▼
SELECT Concat(RTrim(vend_name), ' (',
RTrim(vend_country), ')') AS vend_title
FROM Vendors
ORDER BY vend_name;
analysis ▼
SELECT The statement itself is the same as previously used , Only the calculation field here is followed by the text
Ben AS vend_title . It indicates SQL Create a named... That contains the specified calculation result
vend_title Calculation field of . You can see from the output , The result is the same as before , But now
In the column named vend_title , Any client application can reference this column by name , It's like
It is an actual table column like .
explain :AS Usually optional
In many DBMS in , AS Keywords are optional , But it's best to use it , This is considered a
Best practices .
Tips : Other uses of aliases
Aliases have other uses . Common uses include the inclusion of illegal in actual table column names
character ( Such as space ) Rename it when , When the original name is ambiguous or easily misunderstood
Charge it .
Be careful : Alias
The alias name can be a word , It can also be a string . If it's the latter ,
String should be enclosed in quotation marks . Although this practice is legal , But it's not recommended .
Multi word names are highly readable , However, it will bring various problems to the client application . therefore ,
The most common use of aliases is to rename the column name of multiple words to the name of one word .
explain : Export column
Aliases are sometimes referred to as export columns (derived column), Anyway , They represent
Is the same thing .
7.3 Perform arithmetic calculations
Another common use of calculation fields is to perform arithmetic calculations on the retrieved data . for instance ,
Orders The table contains all orders received , OrderItems The table contains the items in each order
goods . Below SQL Statement to retrieve the order number 20008 All of the items in :
Input ▼
SELECT prod_id, quantity, item_price
FROM OrderItems
WHERE order_num = 20008;
Output ▼
prod_id quantity item_price
---------- ----------- ---------------------
RGAN01 5 4.9900
BR03 5 11.9900
BNBG01 10 3.4900
BNBG02 10 3.4900
BNBG03 10 3.4900
item_price The column contains the unit price of each item in the order . The prices of the items are summarized below ( Unit price times order quantity ):
Input ▼
SELECT prod_id,
quantity,
item_price,
quantity*item_price AS expanded_price
FROM OrderItems
WHERE order_num = 20008;
Output ▼
prod_id quantity item_price expanded_price
---------- ----------- ------------ -----------------
RGAN01 5 4.9900 24.9500
BR03 5 11.9900 59.9500
BNBG01 10 3.4900 34.9000
BNBG02 10 3.4900 34.9000
BNBG03 10 3.4900 34.9000
analysis ▼
The... Shown in the output expanded_price A column is a calculated field , This calculation is quantity*
item_price . Client applications can now use this new computed column , Just like using other columns
equally .
SQL Support table 7-1 The basic arithmetic operators listed in . Besides , Parentheses can be used to distinguish between good and bad
Order first . Introduction to priorities , Please refer to the first 5 course .
surface 7-1 SQL arithmetic operator
fuck do operator say bright
+ Add
- reduce
* ride
/ except
Tips : How to test and calculate
SELECT The statement is test 、 Test functions and calculations provide a good way . although SELECT
Usually used to retrieve data from tables , But omitted FROM Clause is followed by a simple access and
Processing expressions , for example SELECT 3 * 2; Will return 6 , SELECT Trim(' abc ');
Will return abc , SELECT Curdate(); Use Curdate() Function returns the current date
And time . Now you see , It can be used as needed SELECT Statement to verify .
边栏推荐
- 开启生态新姿势 | 使用 WrodPress 远程附件存储到 COS
- Is it safe to open an account and buy stocks? Who knows
- Shell command used in actual work - sed
- MySQL usage notes 1
- squid代理服務器
- Experience Navicat premium 16, unlimited reset, 14 day trial method (with source code)
- Love math experiment | Issue 8 - building of Singapore house price prediction model
- 农产品期货怎么做怎么开户,期货开户手续费多少,找谁能优惠手续费?
- What is a low code development platform? Why is it so hot now?
- Dictionary tree (review)
猜你喜欢

SQL server for circular usage
![[STL programming] [common competition] [Part 1]](/img/ce/4d489e62d6c8d16134262b65d4b0d9.png)
[STL programming] [common competition] [Part 1]

mysql使用笔记一

A set of system to reduce 10 times the traffic pressure in crowded areas

Flood fighting and disaster relief, overcoming difficulties, and City United premium products rushed to the aid of Yingde to donate loving materials

划重点!国产电脑上安装字体小技巧

VMware vSphere ESXi 7.0安装教程

本周二晚19:00战码先锋第8期直播丨如何多方位参与OpenHarmony开源贡献

Recommended practice sharing of Zhilian recruitment based on Nebula graph

抗洪救灾,共克时艰,城联优品驰援英德捐赠爱心物资
随机推荐
Ceph分布式存储
Release of global Unicorn list in 2021: the full list of 301 Unicorn enterprises in China is coming!
Scrum和看板的区别
Squid proxy server
强制 20 天内开发 APP 后集体被裁,技术负责人怒批:祝“早日倒闭!”
Leetcode 1381. Design a stack that supports incremental operations
Prospects for enterprise digitalization (38/100)
Day8 ---- 云资讯项目介绍与创建
MySQL速成——第一天--基础入门
Shell script controls the startup and shutdown of services - with detailed cases
This is the same as data collection. Can you define a parameter as last month or the previous day, and then use this parameter in SQL?
College graduation thesis management system based on wechat applet graduation design
Share an experience of self positioning + problem solving
Necessary software tools in embedded software development
爱数课实验 | 第九期-利用机器学习方法进行健康智能诊断
SQL必需掌握的100个重要知识点:使用函数处理数据
Navicat premium connection problem --- host 'XXXXXXXX' is not allowed to connect to this MySQL server
Graduation design of police report convenience service platform based on wechat applet
Recommended practice sharing of Zhilian recruitment based on Nebula graph
Tutorial | fNIRS data processing toolkit homer2 download and installation