我有一个表(让我们说表)有4列 -
Product_ID, Designer, Exclusive, Handloom
ID是主键,其他3列的值为0或1。
例如 - 0
中的Designer
表示产品不是设计师,1
表示它是设计师。
我想写下一个查询,从给定的16行中选择6行,包含>=4 Designer
,>=4 Exclusive
和>=4 Handloom
个产品。从顶部开始的6行,不仅限于前6行(因为可以有多个组合,所以我们将从顶部开始)
我无法找到明确的解决方案。以下是表格的数据:
Code Designer Exclusive Handloom
A 1 0 1
B 1 0 0
C 0 0 1
D 0 1 0
E 0 1 0
F 1 0 1
G 0 1 0
H 0 0 0
I 1 1 1
J 1 1 1
K 0 0 1
L 0 1 0
M 0 1 0
N 1 1 0
O 0 1 1
P 1 1 0
如果我手动解决,结果将是Product_ID: a,f,i,j,n,o
答案 0 :(得分:1)
这会非常慢吗?
select t1.Code, t2.Code, t3.Code, t4.Code, t5.Code, t6.Code
from Table t1, Table t2, Table t3, Table t4, Table t5, Table t6
where t1.Code < t2.Code and t2.Code < t3.Code
and t3.Code < t4.Code and t4.Code < t5.Code and t5.Code < t6.Code
and t1.Designer + t2.Designer + t3.Designer + t4.Designer + t5.Designer + t6.Designer >= 4
and t1.Exclusive + t2.Exclusive + t3.Exclusive + t4.Exclusive + t5.Exclusive + t6.Exclusive >= 4
and t1.Handloom + t2.Handloom + t3.Handloom + t4.Handloom + t5.Handloom + t6.Handloom >= 4
order by t1.Code, t2.Code, t3.Code, t4.Code, t5.Code, t6.Code
limit 1;
您似乎希望按字母顺序排列的产品代码组合满足您的条件。我不知道6路交叉连接是否会成为性能问题,但我相信它符合要求并且可能是合理的起点。
根据您对数据的了解程度,您可以通过消除仅设置单个标志的行(以及行组合总数)来提高性能。
我在SQL Server上试过这个。没有一行的限制,它返回157匹配。 AFIJNP是69号。其中有7个包括B,其中第一个是ABDIJO。如果我将查询更改为首先在t6.Code上排序,则结果为ADEFIJ。因此,我不知道我是否理解了您的要求。
答案 1 :(得分:0)
SELECT Product_ID, Designer, Exclusive, Handloom
FROM table-name
WHERE Designer <> 0
AND (Exclusive <> 0 OR Handloom <> 0)
LIMIT 6 ;
答案 2 :(得分:0)
我不太确定我理解这个问题......这张桌子还有什么比我们看到的更多?这就是我想你想要的:
select Product_ID,
SUM(Designer) as Designer_cnt,
SUM(Exclusive) as Exclusive_cnt,
SUM(Handloom) as Handloom_cnt
from myTable
group by Product_ID
having Designer_cnt >= 4
or Exclusive_cnt >= 4
or Handloom_cnt >= 4
如果您希望所有3列的总数为4,请将or
子句中的having
更改为and
。