EDIT 12年2月10日:修訂的查詢,以對應於修改後的輸出樣本:
-- Set up the test data.
declare @AmalgamatedStuff as table (ItemId int, Price int, MaxPeople int, CalculationUnit varchar(16))
insert into @AmalgamatedStuff (ItemId, Price, MaxPeople, CalculationUnit) values
(1, 10, 4, 'people/item'),
(2, 70, 2, 'item'),
(3, 30, 8, 'week/item'),
(4, 50, 2, 'week')
-- Stored procedure parameters.
declare @Days as int = 5
declare @Items as int = 2
-- The query.
select ItemId, Price,
case CalculationUnit
when 'item' then Price * @Items
when 'people/item' then Price * MaxPeople * @Items * @Days
when 'week' then round(Price * @Days/7.0, 2)
when 'week/item' then round(Price * @Items * @Days/7.0, 2)
else NULL
end as Total
from @AmalgamatedStuff
注意42.857142失敗舍入到42.85第三結果排。
編輯:銘記列和未指定的計算可變數量的建議的結果不能得到:
-- Set up the test data.
declare @AmalgamatedStuff as table (ItemId int, Price int, MaxPeople int, CalculationUnit varchar(16))
insert into @AmalgamatedStuff (ItemId, Price, MaxPeople, CalculationUnit) values
(1, 10, 4, 'people/item'),
(2, 70, 2, 'item'),
(3, 30, 8, 'week/item'),
(4, 50, 2, 'week')
-- Stored procedure parameters.
declare @Days as int = 5
declare @Items as int = 2
-- The query, give or take the correct calculations.
declare @SpuriousFactorToGetSuggestedResult as int = 2
select ItemId, Price,
case CalculationUnit
when 'item' then Price * @Items
when 'people/item' then Price * MaxPeople * @Items * @Days
when 'week' then Price * @Items * @Days/7
when 'week/item' then Price * @Items * @Days * @SpuriousFactorToGetSuggestedResult/7
else NULL
end as Total
from @AmalgamatedStuff
實際得到的查詢到存儲過程中被留下作爲一個練習OP。
「設計」仍然處於腐臭之下,並且腐爛速度更快。
編輯:回答了「問題」的早期編輯下面仍然是:
你可以使用CASE之類的東西:
select ItemId, Price,
case
when CalculationUnit = 'day' then @Days * Price
when CalculationUnit = 'week' then @Days/7 * Price
else NULL
end as 'Total'
from MyIllConceivedTable
如前所述,這是一個不好的設計。
在某些情況下,查找表可能是有意義的,例如,可以讓你將各種度量單位映射到一些公共基地。考慮體重和他們的克當量。 (也是存儲全名「Ounces」和縮寫「Oz」的方便之處,...)。您的數據表將包含對單位表的引用。
在某些情況下,它可能對時間單位有意義。計劃的事件可能每天,每週,每月,每季度和每年發生。單位的長度有些靈活,用途往往是奇特的。 (我每個月的第3個週三吃午飯,在那裏見?)
關於性能,返回結果的計算結果並不差。您可以使用計算列或視圖來實現您的(惡意)結束。當您爲每行調用函數時,性能會受到影響,例如一個將DATETIME列轉換爲字符串並使用LIKE來確定字符串中是否存在'R'的WHERE子句。
無論你選擇,請不要使用任何的達菲爲:
declare @Today as Date
set @Today = SysDateTime()
select @Today,
DateDiff(day, @Today, DateAdd("day", 1, @Today)) as 'Days in a Day',
DateDiff(day, @Today, DateAdd("week", 1, @Today)) as 'Days in a Week',
DateDiff(day, @Today, DateAdd("month", 1, @Today)) as 'Days in a Month' -- Sometimes!
面臨的挑戰之一,以書面形式產生期望結果的查詢是前兩個結果行有三列wihle最後兩個結果行有四個。大多數查詢爲每一行返回相同數量的列。 – HABO
@ user92546看起來像沒有尾隨空格的逗號是小數點分隔符(檢查計算)... –