【发布时间】:2014-09-08 16:38:23
【问题描述】:
我在以下表格中添加了一些数据:
create table dbo.Products
(
Id int identity not null primary key clustered (Id),
Name nvarchar (120) not null,
Price decimal (19,4) not null
);
create table dbo.AllowedQuantities
(
Id int identity not null primary key clustered (Id),
Quantity float not null
);
create table dbo.ProductsAllowedQuantities
(
ProductId int not null,
QuantityId int not null,
constraint ProductIdQuantityId primary key clustered (ProductId, QuantityId)
);
alter table dbo.ProductsAllowedQuantities
add constraint CProductId foreign key (ProductId) references Products(Id),
constraint CQuantityId foreign key (QuantityId) references AllowedQuantities(Id);
insert into dbo.AllowedQuantities (Quantity) VALUES (0.5), (1), (2)
insert into dbo.Products (Name, Price) VALUES ('A', 400), ('B', 500), ('C', 800), ('D', 1000), ('E', 1200), ('F', 1400)
insert into dbo.ProductsAllowedQuantities (ProductId, QuantityId) VALUES (1, 1), (1, 2)
insert into dbo.ProductsAllowedQuantities (ProductId, QuantityId) VALUES (2, 1)
insert into dbo.ProductsAllowedQuantities (ProductId, QuantityId) VALUES (3, 1), (3, 3)
insert into dbo.ProductsAllowedQuantities (ProductId, QuantityId) VALUES (4, 2), (4, 3)
insert into dbo.ProductsAllowedQuantities (ProductId, QuantityId) VALUES (5, 1), (5, 3)
insert into dbo.ProductsAllowedQuantities (ProductId, QuantityId) VALUES (6, 2)
我使用了以下查询:
select p.Name, p.Price, aq.Quantity, TotalPrice = p.Price * aq.Quantity
from dbo.Products as p
join dbo.ProductsAllowedQuantities as paq
on p.Id = paq.ProductId
join dbo.AllowedQuantities aq
on paq.QuantityId = aq.Quantity
并得到以下数据:
注意 1 奇怪的是 Quantity = 0.5 没有出现......我错过了什么?
目标
给定总价格 TP = { 700, 1900 } 我需要为每个产品随机找到一种产品。
对于给定的每个总价格,我设置了 +/- 200 的范围。所以范围是: 700 > [500, 900]
1900 > [1700, 2100]-
查看表格,我看到了符合这些条件的值:
700 > [500, 900] > 第 2 到 4 行
1900 > [1700, 2100] > 第 5 行 所以我会随机选择 2 到 4 行和第 5 行。
注意 2 如果可能,我希望每个选择包含不同的行。
如果解决方案是:
700 > [500, 900] > 第 2 到 4 行
1900 > [1700, 2100] > 第 4 和 5 行
如果第 4 行被选中,我希望只被选中一次。
我不确定这是否可能......
所以我正在寻找最有效的方法来做到这一点。
如果有必要,通过更改方案或添加一些索引来改进我的数据库...
【问题讨论】:
-
您似乎向我们提出了一系列要求,并要求我们为您编写查询。我建议您尽最大努力,如果遇到速度缓慢,请进行一些基本的性能调整,然后如果您仍然遇到问题,请回到这里提出有关性能的具体问题。
-
除了定义你需要什么...have you tried anything来解决问题?
-
我正在使用 T-SQL 创建一个完整的示例。很快就会更新我的问题。
-
我刚刚用代码和数据更新了我的问题...我还添加了用于查找每种产品的可用总价的查询,但我不确定如何过滤它...
标签: sql sql-server