Jump to content

Recommended Posts

Hi,

 

I'm not sure if this is the best place to ask but I have a query I have written in MySQL, and I need to convert it to MSSQL, does anyone have experience of this?

SELECT DATE_FORMAT(DateReported, '%b %Y') AS DateReported, DATE_FORMAT(DateCompleted, '%b %Y') AS DateCompleted, LocationName,
        IF(status = 'open', 1, 0) AS open,
        IF(status = 'closed', 1, 0) AS closed,
        IF(status = 'cancelled', 1, 0) AS cancelled
    FROM event
    GROUP BY DATE_FORMAT(DateReported, '%b %Y'), LocationName
    ORDER BY FIELD(DATE_FORMAT(DateReported, '%M'), 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
Link to comment
https://forums.phpfreaks.com/topic/277407-convert-query-to-mssql/
Share on other sites

Thanks for your reply, I have managed to convert the date columns (after a lot of hassle!):

SUBSTRING(CONVERT(VARCHAR(20), Event.ReportedDateTime, 113), 4,  AS [DateReported],

My main issue the IF statements which I have attempted to rewrite as

 

CASE Event.Status
  WHEN 'OPEN' THEN 'OPEN'
  WHEN 'CLOSED' THEN 'CLOSED'
  ELSE 'CANCELLED'
END

also I keep getting errors for not grouping some of the columns:

is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

MySQL is far more lenient with GROUP syntax than MSSQL. With MSSQL, if it is in the query it must either be one of the aggregated columns or it must be in the GROUP BY clause

 

As you aren't doing any aggregations (SUM, COUNT etc) why are you using GROUP BY in the first place?

This bit:

IF(status = 'open', 1, 0) AS open,
        IF(status = 'closed', 1, 0) AS closed,
        IF(status = 'cancelled', 1, 0) AS cancelled
would translate as:

CASE WHEN status='open' THEN 1 ELSE 0 END as open,
CASE WHEN status='closed' THEN 1 ELSE 0 END as closed,
CASE WHEN status='cancelled' THEN 1 ELSE 0 END as cancelled
Then you have three separate 1/0 columns, one for each status. Same as the original query.
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.