Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use to_char function functionality in MySQL

I have a table tine_by_day and I know how to use TO_CHAR function in oracle, but how to get same output if I use in MySQL?

Is there any conversion function in MySQL for TO_CHAR()?

I have already tried date_format instead to_char but I'm not getting sufficient results.

SELECT
    to_char(t.the_date,'mm-DD-YYYY') Date,
    SUM(sf7.unit_sales) UnitSales,
    SUM(sf7.store_sales) StoreSales,
    SUM(sf7.store_cost) StoreCost
FROM time_by_day t INNER JOIN sales_fact_1997 sf7 ON t.time_id=sf7.time_id
WHERE
    to_char(t.the_date,'YYYY-MM-DD')>='2012-01-01'
    AND
    to_char(t.the_date,'YYYY-MM-DD')<='2012-01-07'
GROUP BY t.the_date
ORDER BY t.the_date
like image 516
sam140 Avatar asked Aug 03 '26 16:08

sam140


1 Answers

In SQL Server, you would typically use the convert() function, which is not nearly as convenient as to_char(). For your query, you only need it in the select clause:

SELECT convert(varchar(10), t.the_date, 110) as Date,
       SUM(sf7.unit_sales) as UnitSales,
       SUM(sf7.store_sales) as StoreSales,
       SUM(sf7.store_cost) as StoreCost
FROM time_by_day t INNER JOIN
     sales_fact_1997 sf7
     ON t.time_id = sf7.time_id
WHERE t.the_date >='2012-01-01' AND
      t.the_date <= '2012-01-07'
GROUP BY t.the_date
ORDER BY t.the_date;

SQL Server will normally treat the ISO standard YYYY-MM-DD as a date and do the conversion automatically. There is a particular internationalization setting that treats this as YYYY-DD-MM, alas. The following should be interpreted correctly, regardless of such settings (although I would use the above form):

WHERE t.the_date >= cast('20120101' as date) AND
      t.the_date <= cast('20120107' as date)

EDIT:

In MySQL, you would just use date_format():

SELECT date_format(t.the_date, '%m-%d-%Y') as Date,
       SUM(sf7.unit_sales) as UnitSales,
       SUM(sf7.store_sales) as StoreSales,
       SUM(sf7.store_cost) as StoreCost
FROM time_by_day t INNER JOIN
     sales_fact_1997 sf7
     ON t.time_id = sf7.time_id
WHERE t.the_date >= date('2012-01-01') AND
      t.the_date <= date('2012-01-07')
GROUP BY t.the_date
ORDER BY t.the_date;
like image 140
Gordon Linoff Avatar answered Aug 06 '26 06:08

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!