我遇到下面的问题而不确定如何排序: 我们在数据库中有一个框的尺寸: L,W,H
由于可以在随机位置测量框,例如可以将长度的值分配到高度列等。 现在,我们有一个盒子带,其中包含两个与尺寸有关的条件:
频段: 每盒最大24x34x6 要么 每盒最大为21x21x21
要通过AND来计算,OR语句是可能的,但我们最终只会为第一个条件提供100行代码,因为组合的数量将是27,然后这将需要应用于每个列H,L,W的sql语句。 我设法通过交叉连接获得组合总数,但是如何将其应用于CASE语句并获得合理的性能和代码量?
CREATE TABLE #XMS1
( XMS1 int)
INSERT #XMS1 select 6
INSERT #XMS1 select 24
INSERT #XMS1 select 34
select
a.XMS1 as H,
b.XMS1 as L,
c.XMS1 as W
from #XMS1 as a
cross join #XMS1 b
cross join #XMS1 c
L,W,H的值可以是从0到100,但我只需要选择适合乐队的行...
答案 0 :(得分:1)
<强>的Oracle 强>:
您可以使用它来订购尺寸,然后只过滤最小,中间和最大尺寸:
SELECT *
FROM (
SELECT LEAST( l, w, h ) AS small,
l + w + h - LEAST( l, w, h ) - GREATEST( l, w, h ) AS middle,
GREATEST( l, w, h ) AS large
FROM your_box_dimensions_table
)
WHERE ( small <= 6 AND middle <= 24 AND large <= 36 )
OR ( small <= 21 AND middle <= 21 AND large <= 21 ) -- or more simply: large <= 21
SQL Server :
从SQL Server does not appear to have a LEAST
or GREATEST
function开始,您可以使用三个输入为LEAST
和GREATEST
编写用户定义的函数,然后调用它来模仿Oracle解决方案。
或者:
SELECT *
FROM (
SELECT CASE
WHEN l <= w AND l <= h THEN l
WHEN w <= h THEN w
ELSE h
END AS small,
CASE
WHEN w <= l AND l <= h THEN l
WHEN h <= l AND l <= w THEN l
WHEN l <= w AND w <= h THEN w
WHEN h <= w AND w <= l THEN w
ELSE h
END AS middle,
CASE
WHEN l >= w AND l >= h THEN l
WHEN w >= h THEN w
ELSE h
END AS large
FROM your_box_dimensions_table
)
WHERE ( small <= 6 AND middle <= 24 AND large <= 36 )
OR ( small <= 21 AND middle <= 21 AND large <= 21 ); -- or more simply: large <= 21
答案 1 :(得分:1)
丹尼尔,我认为@ MT0已经回答了这个问题,所以不要将此作为答案,我只是简单地将他的答案扩展为一个完整的例子。
第一步是构建1到100之间的值列表,以帮助创建包含框尺寸的表。
DECLARE @n TABLE (n int)
INSERT INTO @n
SELECT ones.n + 10*tens.n +1
FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n)
ORDER BY 1
现在创建一个物理表框来存储每个盒子尺寸组合(100万条记录)
CREATE TABLE Boxes (d1 int, d2 int, d3 int)
INSERT INTO Boxes
SELECT a.n, b.n, c.n
FROM @n a
cross join @n b
cross join @n c
现在在这个表上创建一个带有三个附加列的视图,这些列将按尺寸顺序(小中,大)保存尺寸(感谢MT0,因为我无需输入所有内容!)
您也可以使用物理表而不是视图,但如果需求发生变化,这种方式可以提供更大的灵活性。
CREATE VIEW BoxesExtended AS
select
*
, CASE
WHEN d1 <= d2 AND d1 <= d3 THEN d1
WHEN d2 <= d3 THEN d2
ELSE d3
END AS small
, CASE
WHEN d2 <= d1 AND d1 <= d3 THEN d1
WHEN d3 <= d1 AND d1 <= d2 THEN d1
WHEN d1 <= d2 AND d2 <= d3 THEN d2
WHEN d3 <= d2 AND d2 <= d1 THEN d2
ELSE d3
END AS middle
, CASE
WHEN d1 >= d2 AND d1 >= d3 THEN d1
WHEN d2 >= d3 THEN d2
ELSE d3
END AS large
from Boxes
现在我们要做的就是查询视图以获取符合条件的框
SELECT *
FROM BoxesExtended
WHERE (large <=34 and middle <=24 and small <=6)
OR (large <=21 and middle <=21 and small <=21)
你可以通过拥有一个&#39;乐队&#39;来扩展这一点。
的表格BandID BandName MaxSmall MaxMiddle MaxLarge
1 BandA 6 24 36
2 BandA 21 21 21
3 BandB 30 40 50
然后将其加入BoxesExtended视图。这将允许您定义波段,然后查看视图以获取每个BandName
中的匹配框