SQL Count

This forum helped me create the following query:

select userid, count(userid) as countofuserid
from tblSyDBAudit
where ChangeDate >= Convert(datetime, '2015-01-01') and
keydata like '%docx' and
Action like 'insert' and
TableChanged like 'tblCsDocument' group by userid

The query works great.  It is basically counting the number of documents (.docx) users are creating after a specified date.  As you can see, it is actually counting the number userids.  The query only counts .docx.  However, users also create documents with the .doc extension as well.  I have to manually run the query for both types of doc extensions (.doc and .docx) then add the results together.  I am lazy, and I would like to the query to include both extensions, so I do not have to run it twice.  I have tried getting the syntax to work, but I keep running into errors.  If this does not make sense please let me know.  Thanks in ad

July 6th, 2015 10:23pm

SELECT userid, count(userid) as countofuserid
FROM tblSyDBAudit
WHERE ChangeDate >= '2015-01-01 00:00:00.000'
	and (keydata like '%docx' or keydata like '%doc')
	and Action = 'insert' 
	and TableChanged = 'tblCsDocument' 
GROUP BY userid

Or to show by userid and type:

SELECT userid, 
	CASE WHEN keydata like '%docx' THEN 'DOCX' WHEN keydata like '%doc' THEN 'DOC' ELSE '' END as Type,
	count(userid) as countofuserid
FROM tblSyDBAudit
WHERE ChangeDate >= '2015-01-01 00:00:00.000'
	and (keydata like '%docx' or keydata like '%doc')
	and Action = 'insert' 
	and TableChanged = 'tblCsDocument' 
GROUP BY userid, CASE WHEN keydata like '%docx' THEN 'DOCX' WHEN keydata like '%doc' THEN 'DOC' ELSE '' END

You should also consider not using like when you have no wildcard searches. = is much better for performance.

I hope you found this post helpful! If you did please vote it as helpful on the left. If it answered your question please mark it as the answer below. :)


Free Windows Admin Tool Kit Click here and download it now
July 6th, 2015 10:53pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics