【问题标题】:How to write an if condition in SQL如何在 SQL 中编写 if 条件
【发布时间】:2016-10-25 17:41:14
【问题描述】:

我正在尝试使用 if 条件计算查询,我需要显示两个值作为买入和卖出。

SELECT
    n.Date as Date,
    n.dp_id as DP_ID,
    cast(n.emp_no as nchar) as emp_no,
    n.holder as HOLDER,
    n.add1 as ADD1,
    n.add2 as ADD2,
    n.add3 as ADD3,
    n.add4 as ADD4,
    n.pin as PIN,
    'emp_table' as rec_type,
    (
    select s.position from emp_table as s
    where s.emp_no = n.emp_no
    and s.dp_id = n.dp_id
    and s.Date < n.Date
    order by s.emp_no,s.Date desc
    limit 0,1
    ) as OPEN_BAL,
    n.position as CLOS_BAL
    FROM emp_table as n
    where true
    and n.Date >= '2013-02-01'
    and n.Date <= '2013-02-8'

----up to this it was working if condition part not working----- 
(select
    open_bal,
    if(open_bal<clos_bal,clos_bal-open_bal,0) as buying,
    if(open_bal>clos_bal,open_bal-clos_bal,0) as selling,
    order by buying desc from emp_table
)

【问题讨论】:

标签: mysql sql


【解决方案1】:

您可以使用CASE 代替if-condition

SELECT   ...,
         CASE WHEN open_bal < clos_bal THEN ID ELSE open_bal END AS ColumnName,
         ...
FROM     emp_table

【讨论】:

  • select n.holder,( CASE WHEN open_balclos_bal,open_bal-clos_bal THEN "Selling" END)) 作为 emp_table 的状态仍然没有得到帮助我要输出吗?
猜你喜欢
  • 1970-01-01
  • 2011-12-23
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 2011-08-08
  • 1970-01-01
  • 2016-04-17
  • 2016-12-06
相关资源
最近更新 更多