简体   繁体   中英

how to concat a $ to a particular string

this is my program in output there is $ will not printed. i will use correct syntex as '$'+ but it doesn't work

SELECT USERS.ID,CONCAT(USERS.FIRSTNAME,' ',USERS.LASTNAME)AS USERNAME,
     ('$'+ SUM(CPS_HISTORY.CHARGED_AMOUNT+CPS_HISTORY.TRANSACTION_FEE+CPS_HISTORY.SERVICE_CHARGE+CPS_HISTORY.COMBO_PAK_PRICE))AS REVENUE FROM USERS JOIN CPS_HISTORY ON CPS_HISTORY.SUBSCRIBER_ID = USERS.ID GROUP BY USERS.ID ORDER BY REVENUE DESC LIMIT 5;

+---------+---------------+---------+
| ID      | USERNAME      | REVENUE |
+---------+---------------+---------+
| 1803399 | Michael Rowan |     772 |
| 1697091 | NULL          |     676 |
| 1790000 | ree Green     |     626 |
| 1766654 | Jose M NUFIO  |     625 |
| 1731854 | Ashlee Durgin |     622 |
+---------+---------------+---------+
5 rows in set, 13305 warnings (0.15 sec)

the problem with concat function is: changed data.

+---------+-----------------+---------+
| ID      | USERNAME        | REVENUE |
+---------+-----------------+---------+
| 1753814 | Joseph Hearn    | $99     |
| 1806377 | Gideon Anderson | $99     |
| 1800992 | Camryn Revitte  | $99     |
| 1802344 | Tanner Chik     | $99     |
| 1594358 | NULL            | $99     |
+---------+-----------------+---------+
5 rows in set (0.00 sec)

use concat to concatinate the values:

SELECT USERS.ID,CONCAT(USERS.FIRSTNAME,' ',USERS.LASTNAME)AS USERNAME,
     concat('$', SUM(CPS_HISTORY.CHARGED_AMOUNT+CPS_HISTORY.TRANSACTION_FEE+CPS_HISTORY.SERVICE_CHARGE+CPS_HISTORY.COMBO_PAK_PRICE))AS REVENUE 
     FROM USERS JOIN CPS_HISTORY ON CPS_HISTORY.SUBSCRIBER_ID = USERS.ID GROUP BY USERS.ID ORDER BY REVENUE DESC LIMIT 5;

The data is not changed, only the type.

You are ordering by your REVENUE column, which was numerical before, but now, after the CONCAT() , it is a string. And $99 as a string comes before $772 (if sorted DESC).

There are two solutions:

  1. Add the $ in your application instead in SQL, or
  2. Work with a sub query which does the data picking and ordering in the inner query and the formatting in the outer one.

    Something like

     SELECT ID, USERNAME, CONCAT('$', REVENUE) AS REVENUE FROM (SELECT USERS.ID,CONCAT(USERS.FIRSTNAME,' ',USERS.LASTNAME) AS USERNAME, SUM(CPS_HISTORY.CHARGED_AMOUNT+CPS_HISTORY.TRANSACTION_FEE+CPS_HISTORY.SERVICE_CHARGE+CPS_HISTORY.COMBO_PAK_PRICE)) AS REVENUE FROM USERS JOIN CPS_HISTORY ON CPS_HISTORY.SUBSCRIBER_ID = USERS.ID GROUP BY USERS.ID ORDER BY REVENUE DESC LIMIT 5) AS INNER 

    should do. (Untested!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM