mysql遇到的问题总结(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/boniesunshine/article/details/79953855

  

前言

  最近使用finereport做报表,涉及到好多sql的处理,下面是用到的sql的总结,sql有好多东西都是没用过的。

sql总结

1.
  if

表达式:IF( expr1 , expr2 , expr3 )

expr1条件,条件为true,则值是expr2 ,false,值就是expr3

示例:

if(len(buyer)==0,"","and od.BUYER_CUSTOMER_NAME ='"+buyer+"'")

2.

  case when

  case 列名

  when 条件 then 结果

  else 其它结果

  end 别名

  示例:

CASE od.`STATUS`

WHEN '05' THEN

    '已成交'

WHEN '10' THEN

    '已租船'

WHEN '15' THEN

    '已装船'

WHEN '20' THEN

    '已到港'

WHEN '25' THEN

    '已卸货'

WHEN '30' THEN

    '已对账'

WHEN '35' THEN

    '已收款'

WHEN '00' THEN

    '已取消'

END AS "状态"

3.

  ifnull

IFNULL( expr1 , expr2 )

在 expr1 的值不为 NULL的情况下都返回 expr1,否则返回 expr2

  示例:

CONCAT('$',IFNULL((select FORMAT(max(statement.SETTLEMENT_PRICE), 3) from t_order_statement statement where od.ID = statement.ORDER_ID and statement.STATEMENT_TYPE = '2' and statement.alive_flag = '1'),

  (select FORMAT(max(statement.SETTLEMENT_PRICE), 3) from t_order_statement statement where od.ID = statement.ORDER_ID and statement.STATEMENT_TYPE = '1' and statement.alive_flag = '1'))) AS "结算价格",

4.

  concat

  示例:

CONCAT(

        '+/-',

        FORMAT(goods.MORE_LESS, 0),

        '%'

    ) AS "溢短装",
CONCAT(

        transport.DELIVERY_DATE_START,

        '至',

        transport.DELIVERY_DATE_END

    ) AS "装期",

5.

  排名

  片段示例:

select channelName,browseMonth,

CASE

WHEN @coltotal = oriInfo.browseWeek THEN

    @colnum

WHEN @coltotal := oriInfo.browseWeek THEN

    @colnum :=@colnum + 1

WHEN @coltotal = 0 THEN

    @colnum :=@colnum + 1

END AS monthOrder

from 

(SELECT @colnum := 0 ,@coltotal := NULL)t,

6.

  本月第一天,最后一天
  函数:

select curdate();                       --获取当前日期
select last_day(curdate());                    --获取当月最后一天。
select DATE_ADD(curdate(),interval -day(curdate())+1 day);   --获取本月第一天
select date_add(curdate()-day(curdate())+1,interval 1 month); -- 获取下个月的第一天
select DATEDIFF(date_add(curdate()-day(curdate())+1,interval 1 month ),DATE_ADD(curdate(),interval -day(curdate())+1 day)) from dual;--获取当前月的天数 

  示例:

select ct.total as "企业总数",cd.day as "企业当天",cm.mon as "企业当月" from
(SELECT COUNT(DISTINCT e.member_id) AS total FROM `enterprises` e WHERE create_time > '2017-01-01' AND create_time < '2020-03-31' 
AND EXISTS (SELECT * FROM members m WHERE m.id = member_id AND m.`del_flg` = FALSE AND m.locked = FALSE)
AND EXISTS (SELECT * FROM `member_credentials` c WHERE c.`member_id`= e.member_id AND c.`credentials_code`='99' AND c.`audit`)) ct,
(SELECT COUNT(*) as day FROM `enterprises` WHERE create_time = curdate()) cd,
(SELECT COUNT(*) as mon  FROM `enterprises` WHERE create_time >= 
DATE_ADD(curdate(),interval -day(curdate())+1 day) and create_time <= 
last_day(curdate())) cm;

小结

  sql中的函数是比较有意思的,学以致用,不断总结!

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页