Friday, March 20, 2009

SQL: Randomly Select One Record from Multiple Categories

This query will randomly select one record from multiple categories that you specify. First the inner select partitions the record set based on a specific field, then order's it randomly by using newid(). The outer select then selects the top row from each category (aka the partioned group). The top record is always random due ordering by newid().

SELECT * FROM (
SELECT
ROW_NUMBER() OVER(PARTITION BY a.Category ORDER BY newid()) AS RowNumber,
*
FROM Table a ) b
WHERE RowNumber = 1

Thursday, March 5, 2009

SQL: More Fun with Unpivot

takes a table like:
date 0 1 2 3 4 5
3/15 a b c d e f

and converts it to

3/15 12:00am a
3/15 1:00am b
3/15 2:00am c

and so on

SELECT dateadd(hour,cast(times AS int),date), cast(times AS int), value

FROM (SELECT date, [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10],
[11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23]
FROM b) AS p
UNPIVOT (value FOR times IN ([0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10],
[11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23]
)) AS s

Thursday, January 8, 2009

@_variable_in

When declaring input variables to a stored procedure in MS SQL Server, it is sometimes beneficial to use

@_variable_in instead of @variable_in

WITH (NOLOCK)

Using the NOLOCK hint can speed up queries by allowing the query to not wait while other queries are writing to the table. The downside is that your query can read data that may get rolled back.

FROM table1 a WITH (NOLOCK)
JOIN table 2 b WITH (NOLOCK) ON a.field = b.field
JOIN table3 c WITH (NOLOCK) ON b.field= c.field
JOIN table4e WITH (NOLOCK)


More info: http://msdn.microsoft.com/en-us/library/ms187373.aspx

Tuesday, December 2, 2008

sql: easy datetime formatting to varchar

convert(varchar, FIELD_NAME, FORMAT_NUMBER_FROM_CHART)

http://msdn.microsoft.com/en-us/library/aa226054(SQL.80).aspx

sql: get just the hour from a datetime

SELECT DATEADD(hh, 13, DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())))

probably a fancier way to keep the hour information, but you can just in an hour variable there to add it back in.

replace getdate() with your date field

Wednesday, October 29, 2008

SQL: Insert from another table

INSERT INTO Table1 (ab)     
SELECT c, d     
FROM Table2     
WHERE c = 'something'