[英]How do I divide a value with a string condition?
我有一個數量(整數)字段和一個名稱(字符串)字段。 如何僅將產品C除以三以返回新數量值? 我因將字符串和整數類型與我嘗試過的所有內容混合在一起而出錯。
Name Quantity New Quantity
Product A 5 5
Product B 35 35
Product C 27 9
這是我正在使用的查詢:
SELECT
chg.name
, sim.Description
, loc.location_name
, Service_Date = CONVERT(DATE, chg.begin_date_of_service)
, sim.Service_Type
, sim.Visit_Type
, sim.Contraceptive_Type
, sim.Lab_Type
, sim.Immunization_Type
, chg.quantity
FROM
charges chg
INNER JOIN PPMNS_Service_Item_Info sim ON chg.name = sim.name
AND chg.begin_date_of_service BETWEEN sim.SIM_Eff_Date AND sim.SIM_Exp_Date
AND ((chg.begin_date_of_service BETWEEN sim.Billing_NDC_Eff_Date AND sim.Billing_NDC_Exp_Date) OR sim.Billing_NDC_Eff_Date = '')
INNER JOIN location_mstr loc ON chg.location_id = loc.location_id
WHERE
chg.link_id IS NULL
AND sim.Visit_Rank < 50
實際上,這並不是很難做到的。 從標記來看,您更有可能在SQL程序(例如Razor或類似的程序)中執行此操作。
Select Quantity, (Quantity / 3)
From table
where name = "PRODUCT C"
那應該就是它的全部了。
如果我理解正確,則可以使用case
語句:
select . . .
(case when name = 'PRODUCT C' then chg.quantity / 3 else chg.quantity
end) as quantity
. . .
請注意,如果兩個操作數都是整數,則SQL Server會進行整數除法。 如果quantity
是整數,並且想要小數位,則可以除以3.0
而不是3
。
如果您使用的是SQL Server 2012或更高版本,則可以將以下列添加到Select語句中
iif(name ='PRODUCT C',Quantity / 3.0,Quantity)newQuantity
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.