I structured my sql table like this:
ItemID Price MaxPeople CalculationUnit
1 10 4 people/item
2 70 2 item
3 30 8 week/item
4 50 2 week
etc.
Now I would like to run a basic stored procedure that looks something like
sp_return_items_total
@Days as int,
@Items as int
AS
select itemid, price, total from table
Total would be a value based on this calculation (number of days * calculation unit * price).
For example for @Days = 5 and ‘@Items = 2’ results would be:
1, 10, 400 (10 * 4 people * 2 items * 5 days)
2, 70, 140 (70 * 1 * 2 items * 1)
3, 30, 42.85 (30 * 1 * 2 items * 5/7 days)
4, 50, 35.71 (50 * 1 * 1 items * 5/7 days)
I am trying to find a solution, how to get the total value based on the sp parameters and calculation unit.
Thanks for participating
EDIT 2/10/12: Revised query to correspond to revised sample output:
Note that 42.857142 fails to round to 42.85 in the third result row.
EDIT: Bearing in mind that the suggested results with a variable number of columns and unspecified calculations cannot be obtained:
Actually getting the query into a stored procedure is left as an exercise for the OP.
The “design” remains somewhere below rancid, and festering ever faster.
EDIT: Answer to an earlier edit of the “question” remains below:
You can do things using a CASE like:
As previously noted, it’s a bad design.
In some cases it might make sense to have a lookup table, e.g. something that lets you map various units of measure to some common base. Think weights and their gram equivalents. (Also a handy place for storing the full name “Ounces” and abbreviation “Oz”, … .) Your data table would contain references to the units table.
In some cases it may make sense with units of time. Scheduled events might recur daily, weekly, monthly, quarterly and annually. The lengths of the units are somewhat flexible, and the uses tend to be peculiar. (I have a lunch on the 3rd Wednesday of each month. See you there?)
Regarding performance, calculations that return results aren’t bad. You could use a computed column or a view to achieve your (nefarious) end. Performance takes a hit when you have functions called for each row, e.g. a WHERE clause that converts a DATETIME column to a string and uses LIKE to determine if there is an ‘R’ in the string.
Whatever you choose, please don’t use anything as daffy as: