Jump to content

[SOLVED] Is this a valid query?


dshevnock

Recommended Posts

I don't have much experience writing mysql statements with IF statements. I did however come up with this one and wanted to know if this query was valid/make sense/logical/etc.

 

SELECT

  sum( IF(pos.created_by= '8',1,0))  AS userOpenedTotalCount,

  sum( IF(pos.updated_by = '8' AND pos_details.closed = 'Y',1,0)) as userClosedTotalCount,

  sum( IF( pos.created_date BETWEEN '2007-07-02 00:00:00' AND '2007-07-02 23:59:59' AND pos.created_by = '8', 1, 0 ) ) AS userOpenedTodayCount,

  sum( IF( pos.last_updated_date BETWEEN '2007-07-02 00:00:00' AND '2007-07-02 23:59:59' AND pos.updated_by = '8' AND pos_details.closed = 'Y', 1, 0 ) ) AS userClosedTodayCount

FROM pos JOIN pos_details ON pos.id = pos_details.id

 

Or is there a better way to write this?

Link to comment
Share on other sites

SELECT 
   SUM( pos.created_by = '8')  AS userOpenedTotalCount, 
   SUM( pos.updated_by = '8' AND pos_details.closed = 'Y') as userClosedTotalCount, 
   SUM( pos.created_date BETWEEN '2007-07-02 00:00:00' AND '2007-07-02 23:59:59' AND pos.created_by = '8') AS userOpenedTodayCount, 
   SUM( pos.last_updated_date BETWEEN '2007-07-02 00:00:00' AND '2007-07-02 23:59:59' AND pos.updated_by = '8' AND pos_details.closed = 'Y' ) AS userClosedTodayCount 
FROM pos JOIN pos_details ON pos.id = pos_details.id

 

It makes sense, and it's a good way to count.  It can be made shorter, though, by using the property of a boolean comparison in MySQL that true=1 and false=0 already.  In other words, if you're just doing an IF(condition,1,0), you don't need the IF() since the comparison will produce either 1 if true or 0 if false anyway.

Link to comment
Share on other sites

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.