SQL Week by Week

Posted on the September 26th, 2008 under SQL by admin

This handy little SQL select statement was given to me by one of the developers I work with. It’s used to look at a date column in a SQL table and see how many rows fall within a given week from the earliest entry. For instance you could see how many subscriptions you have week by week which in turn could be used to assess the quality of your marketing methods. Let’s use that premise for the example.

So the SQL table name is subscribe and the column will be dateAdded

select convert(datetime, convert(varchar(25), dateadd(day, 1-datepart
(weekday, dateadded),dateadded),107)),count(*)
from subscribe
group by convert(datetime, convert(varchar(25), dateadd(day, 1-datepart
(weekday, dateadded),dateadded),107))
order by 1

So this SQL statement should deliver something like this…

6/9/2008 5
13/9/2008 6
20/9/2008 9

This little statement assumes Sunday is the first day of the week but this can be remedied (I’ve been informed).

How to replace a comma with space in SQL

Posted on the September 25th, 2008 under SQL by admin

Background

I came across this issue when dumping the contents of a table into a CSV file from Enterprise Manager. Many people put comma’s into fields when typing their own address or something similar. This means when the CSV is opened many rows of data will be erroneous. So the solution is to replace any comma with a space so the contents of that field are still readable.

Solution

Replace(table.field, ‘,’, ‘ ‘)

*Replace the “table.field” with the applicable table name and field name

This simple bit of code fixes the comma issue and will allow the table to be dumped into a CSV for further manipulation.

So that’s how to replace a comma with a space in SQL