我有一个非常简单的表
ID| Category| Amount
------------------------
1 | Size 1 | 50000.00
2 | Size 2 | 100000.00
3 | Size 3 | 500000.00
当传递的金额小于或等于50000.00时,我想返回类别“大小1” 通过金额时“尺寸2”小于或等于100000.00但大于“尺寸1” 当传递的数量小于或等于500000.00但大于“尺寸2”时,“尺寸3”
这样做的一个显而易见的方法是简单地使用if条件,但这只是一个例子,可以有任意数量的类别。所以我不能硬编码。
答案 0 :(得分:2)
请参阅以下代码
public class TesteStackOverflow
{
public TesteStackOverflow(decimal amout)
{
List<testTable> list = new List<testTable>();
list.Add(new testTable { Id = 1, Category = "Size 1", Amount = 50000 });
list.Add(new testTable { Id = 2, Category = "Size 2", Amount = 100000 });
list.Add(new testTable { Id = 3, Category = "Size 3", Amount = 500000 });
var r = (from n in list where amout <= n.Amount select n).First();
if(r != null)
System.Diagnostics.Debug.Print(r.Category);
else
System.Diagnostics.Debug.Print("Category not found");
}
}
public class testTable
{
public int Id { get; set; }
public string Category { get; set; }
public decimal Amount { get; set; }
}
答案 1 :(得分:1)
一种简单的方式......
SELECT CATEGORY
FROM YourTable
WHERE AMOUNT = (SELECT MAX(AMOUNT)
FROM YourTable
WHERE AMOUNT <= YourValue)
答案 2 :(得分:0)
您可以将限制放在表格中,然后加入它。
答案 3 :(得分:0)
答案 4 :(得分:0)
if not exists(
SELECT TOP 1 *
FROM tbl_TicketSizeMst
WHERe Amount >= @amt
ORDER BY Amount
)
begin
select top 1 * FROM tbl_TicketSizeMst
end
else
begin
SELECT TOP 1 *
FROM tbl_TicketSizeMst1
WHERe Amount >= @amt
ORDER BY Amount
end
答案 5 :(得分:0)
使用以下定义创建视图:
; WITH x AS (
SELECT id
, category
, amount
, Row_Number() OVER (ORDER BY amount) As sequence
FROM your_table
)
SELECT x.id
, x.category
, Coalesce(prev.amount, 0) As lower_amount
, x.amount As upper_amount
FROM x
LEFT
JOIN x As prev
ON prev.sequence + 1 = x.sequence
此视图将返回如下结果集:
id category lower_amount upper_amount
-- -------- ------------ ------------
1 Size 1 0.00 50000.00
2 Size 2 50000.00 100000.00
3 Size 3 100000.00 500000.00
然后您可以像这样查询此视图:
SELECT category
FROM that_view
WHERE @your_value > lower_amount
AND @your_value <= upper_amount
答案 6 :(得分:0)
告诉我哪些样本数据不起作用(失败的地方)
Declare @t table(ID int, Category varchar(50), Amount float)
insert into @t
select 1 , 'Size 1', 50000.00 union all
select 2 , 'Size 2' , 100000.00 union all
select 3 , 'Size 3' , 500000.00
Declare @input float=50000
select id,category ,amount from @t a
where a.Amount-@input=(select min(a.Amount-@input) from @t a where a.Amount-@input>=0 )