0

I Have sql table like this:

Table A

NIP        BIDANG      MAYOR       MINOR
1            A          ZZ          YY
2            A          ZZ          XX
2            A                      YY

and i have another table :

Table B

NIP        Keahlian     Nilai
1             XX          2
1             YY          0
1             ZZ          3
2             XX          4
2             YY          2
2             ZZ          3

Table C
NIP           Score       Limit
1               10          15
2               20          15

Based on that table, i want to create a table with conditional statement like this : if socre <= limit, than saran = xxx else saran = group concat from mayor minor but sorted by the high value in coloumn Nilai in Table B. So, the output like this :

NIP       Saran
1          XXX
2        XX, ZZ, YY

How to make it, please help me.

user3440030
  • 45
  • 1
  • 8

1 Answers1

0

The following query gets you the required output. You can use ORDER BY with the GROUP_CONCAT function. Also, Limit is a reserved word, so I renamed the column as Limitx. Please see this SQL Fiddle.

SELECT
    NIP,
    CASE SIGN(Score-Limitx)
        WHEN -1 THEN 'XXX'
        ELSE (SELECT GROUP_CONCAT(b.Keahlian ORDER BY b.Nilai DESC) FROM TableB b WHERE b.NIP = c.NIP)
    END Saran
FROM
    TableC c;

EDIT:

Here is the modified query, based on the requirement that Keahlian must exist in either MAYOR or MINOR column of TableA:

SELECT
    NIP,
    CASE SIGN(Score-Limitx)
        WHEN -1 THEN 'XXX'
        ELSE (SELECT 
                GROUP_CONCAT(b.Keahlian ORDER BY b.Nilai DESC) 
              FROM TableB b
              INNER JOIN
              (SELECT NIP, MAYOR Keahlian
               FROM TableA
               UNION ALL
               SELECT NIP, MINOR
               FROM TableA 
              ) TableA_list
              ON TableA_list.NIP = b.NIP AND TableA_list.Keahlian = b.Keahlian
              WHERE b.NIP = c.NIP
              )
    END Saran
FROM
    TableC c;

Updated SQL Fiddle

References:

Related Question on SO

Community
  • 1
  • 1
Joseph B
  • 5,519
  • 1
  • 15
  • 19
  • But i want to based on mayor minor, if keahlian has a value that does not exist in table A, then the value will not be displayed in output. – user3440030 Apr 23 '14 at 13:38