SQL SQL語句積累

2021-10-02 16:28:05 字數 2022 閱讀 8959

實際案例

例:結果集中,name=胡聰 age=23 性別=男,想要輸出diy欄位

select su.name ,su.age ,su.*** , concat('姓名', su.name,'年齡',su.age, '性別',su.***) as memo

from sys_user

輸出:

name

age***

memo

胡聰23

男姓名胡聰年齡23性別男

sql round() 語法:select round(column_name,decimals) from table_name

column_name:需要四捨五入的欄位名 decimals:保留的小數字數

需求:需要統計指定時間內,榜單材料的重量佔比,並按高低進行排序

思路:按材料名稱進行分組,統計出每種材料的總重量,再除以材料總的重量

sql:子查詢作為結果、round()函式、分組group by、排序order by、字串拼接concat()

sql語句:

select

a.materialdetailname,

a.realweight,

concat( round( a.realweight / b.totalrealweight * 100, 2 ), '', '%' ) as percent

from

(select

bbd.material_name as materialdetailname,

ifnull( sum( bbd.real_weight ), 0 ) as realweight

from

bi_bill_detail bbd

left join bi_bill bb on bb.id = bbd.bill_id

where

1 = 1

and bb.del_flag = 0

and bbd.material_name is not null

and bb.office_id in ( 033 )

and bb.in_date >= '2020-01-01 00:00:00'

and bb.in_date <= '2020-12-31 23:59:59'

group by

bbd.material_name

order by

realweight desc

) as a,

(select

ifnull( sum( bbd.real_weight ), 0 ) as totalrealweight

from

bi_bill_detail bbd

left join bi_bill bb on bb.id = bbd.bill_id

where

1 = 1

and bb.del_flag = 0

and bbd.material_name is not null

and bb.office_id in ( 033 )

and bb.in_date >= '2020-01-01 00:00:00'

and bb.in_date <= '2020-12-31 23:59:59'

) as b

輸出:

materialdetailname

realweight

percent

道砟1380.911

32.89%

機制砂1062.64

25.31%

碎石1010.375

24.06%

ab料485.24

11.56%

水泥208.06

4.95%

鋼絞線32.02

0.76%

柴油19.86

0.47%

參考:

SQL SQL語句總結 5

查詢全部 select from table name 查詢指定字段 select column name from table name 注意 如需查詢多個字段,則欄位名之間需要用英文的逗號隔開。定義欄位起別名 select column name as 別名 from table name 去重...

SQL SQL語句總結 2

建立資料庫 create database name 開啟資料庫 use database name 修改資料庫 alter database name 刪除資料庫 drop database name 顯示資料庫結構 show database name 顯示資料庫中所有的表 show table...

SQL語句積累 三

起別名不能用數字 select from table1 1,table2 2是不允許的.用a,b代替吧.stuff 要替換的字串,起始位置,長度,替換內容 select stuff abcdef 2,3,ijklmn goif object id tempdb.is not null drop ta...