2016-06-23 11 views
0

Ich versuche, die Abfrage zu berechnen, wenn Bedingung, ich zwei Werte als Kauf und Verkauf zeigen müssen.Wie schreibe ich eine if-Bedingung in SQL

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 
) 
+0

[control-Flow-Funktionen] (http://dev.mysql.com/doc/refman/5.7/en/control- flow-functions.html) sollte dein Freund sein –

+0

Mögliches Duplikat von [Verwendung einer IF-Anweisung in einer MySQL SELECT-Abfrage] (http://stackoverflow.com/questions/8444570/using-an-if-statement-in-a- mysql-select-query) –

+1

wo möchten Sie diese Abfrage (unterhalb der Zeile) platzieren? in die Hauptabfrage als abgeleitete Tabelle oder als separate Tabelle? – mitkosoft

Antwort

0

Sie können CASE anstelle der Verwendung if-condition

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

wählen n.holder, (CASE WHEN open_bal clos_bal, open_bal-clos_bal THEN "Verkauf" END)) AS Status von emp_table immer noch nicht helfen mir ausgegeben werden? –

Verwandte Themen