For a user logging table I have in a SQL database, I track the some of the parameters off of a report request. The report allows multiple ID's to be passed to it and I store all of those in a single column in the database column. If this were to be a normalized set of data, there would definitely be an additional table setup for this, but this is what was inherited...
I've now been asked to give a quick count of the number of times a report was run with more than 2 ID's passed to it. I can easily get the number of records that have more than 1 report requested because they all include a comma.
What I need to do next is count the number of times a comma appears in a column. How do you do this in SQL?
--count the number of times more than 1 report was requested in the record select count(*) as cnt from [table] where RequestedReportParams Like '%,%'
The MySQL COUNT() function allows you to count how many times a certain value appears in your MySQL database. The function can also help you to count how many rows you have in your MySQL table. The function has one expression parameter where you can specify the condition of the query.
SELECT LEN(RequestedReportParams) - LEN(REPLACE(RequestedReportParams, ',', '')) FROM YourTable WHERE .....
This is simply comparing the length of the column with the commas, with the length of the value with the commas removed, to give you the difference (i.e. the number of commas)
It seems the quick and dirty way to answer the question you've been asked would be to do this:
select count(*) as cnt FROM [table] WHERE RequestedReportParams Like '%,%,%'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With