最近開發過程中,用到的關於幾個sql查詢的語句,記錄一下
資料表的建立時間是時間戳格式
1、查詢資料表中,每天的資料總量;
select
count(*) as countnumber, //獲取總數
from_unixtime(建立時間,'%y-%m-%d') as datetime //將時間戳轉換為日期輸出
from
表名group by from_unixtime(建立時間,'%y-%m-%d'); //將時間戳轉換為日期輸出
時間段要統一
2、查詢資料表中每種型別的總數以及所佔總數量的百分比
select
count(*) as orders, //總數量
sum(case when type = 4 then 1 else 0 end) as carriage, //當前型別的總數量
cast(100.0 * sum(case when type = 4 then 1 else 0 end) / count(*) as decimal(18, 2)) as carriages, //該數量所佔百分比
sum(case when type = 3 then 1 else 0 end) as grab,
cast(100.0 * sum(case when type = 3 then 1 else 0 end) / count(*) as decimal(18, 2)) as grabs,
sum(case when type = 1 then 1 else 0 end) as assign,
cast(100.0 * sum(case when type = 1 then 1 else 0 end) / count(*) as decimal(18, 2)) as assigns
from 表名;
3、查詢當月新增資料
select
需要查詢的字段,
if(`sd`.`id`,`sd`.`vaild`,`sc`.`state`) as state // if 判斷。。。不想寫了
from
`表1` `su`
left join `表2` `sd` on 鍊錶條件
left join `表3` `sc` on 鍊錶條件
left join `表4` `sur` on 鍊錶條件
left join `表5` `sr` on 鍊錶條件
where
`sur`.`role_id` not in (0,1,4,7) and
`su`.`create_time` between
unix_timestamp(concat(date_format(last_day(now()),'%y-%m-'),'01'))
andunix_timestamp(now()) //時間段在本月初到此刻為止
4、查詢異常資料
select
so.order_no,
sw.driver_name,
su.phone,
concat(sw.from_province,sw.from_city) as from_address, //將兩個查詢字段連線成一條展示
concat(sw.to_province,sw.to_city) as to_address, //同上
from_unixtime(`sw`.`start_shipping_time`,'%y-%m-%d %h:%i') as start_shipping_time, //同 1
from_unixtime(`sw`.`take_time`,'%y-%m-%d %h:%i') as take_time
from
`sys_order` `so`
left join `sys_order_waybill` `sow` on `so`.`id` = `sow`.`order_id`
left join `sys_waybill` `sw` on `sow`.`waybill_id` = `sw`.`id`
left join `sys_driver` `sd` on `sd`.`id` = `sw`.`driver_id`
left join `sys_user` `su` on `sd`.`user_id` = `su`.`id`
where
sw.`status` !=0 and sw.`status` !=-1 and
unix_timestamp(now()) > sw.take_time or sw.arrive_time >sw.take_time //得到當前時間戳
像3、4的這種情況,連表太多,我 都是 直接建立檢視,這樣查詢會快點。
補充建立檢視:
create view 《檢視名》 as
sql原生**好呀!!!!!
sql查詢每天整點時間的資料
資料庫表裡有多個時間資料,只想取每天5分鐘 10分鐘 1小時 4小時整點的資料,其他時間點的不要,sql可以這樣寫 postgresql log time的型別為timestamp 5min整點 select log time from where mod extract minute from l...
SQL的時間戳日期時間轉換
將時間戳轉換為日期格式 比如降1455504268 2016 02 15 10 44 28 1 select device.register time a,from unixtime device.register time,y m d h i s as registertime from tm d...
sql查詢當天 資料
今天的所有資料 select from 表名 where datediff dd,datetime型別字段,getdate 0 昨天的所有資料 select from 表名 where datediff dd,datetime型別字段,getdate 1 7天內的所有資料 select from 表...