我必须构建一个查询来分析商店的“趋势”销售情况。 基本上我需要在购买文章组合时获取,例如: 当购买文章0001时,很可能也会购买文章0002,所以我想检索类似的内容:
article a | article b | occurrences |
--------- | --------- | ----------- |
0001 | 0002 | 1
0001 | 0003 | 0
实际上我有一个表TicketDetails,它存储在每个票证和每个票证中包含的商品代码,如:
store | station | document | consecutive | article
----- | ------- | -------- | ----------- | ------
w | x | y | a | 0001
w | x | y | a | 0002 (same ticket, different article)
w | x | y | b | 0003
请给我关于如何构建此查询的任何建议,我觉得有点迷失。
注意: 如上所示,每张票都是前4列w-x-y-z
的组合答案 0 :(得分:1)
我想你只想要一个自我加入。如果你想要所有文章 - 而不是那些只是在订单中共同发生的文章 - 那么SQL就会有点棘手。
我假设您有一个名为articles
的表,因此您可以先生成所有对:
select a1.article, a2.article, count(td2.article) as occurrences
from articles a1 join
articles a2
on a1.article < a2.article left join -- (a, b) is the same as (b, a)
ticketDetails td1
on td1.article = a1.article left join
ticketDetails td2
on td2.article = a2.article and
td2.store = td1.store and
td2.station = td1.station and
td2.document = td1.document and
td2.consecutive = td1.consecutive
group by a1.article, a2.article;
答案 1 :(得分:1)
将TicketDetails加入到自身,匹配门票,但不同的文章
select t1.article
,t2.article
,Count(t1.article)
from ticketdetails t1
left join ticketdetails t2
on t1.store = t2.store
t1.station = t2.station
t1.document = t2.document
t1.consecutive = t2.consecutive
t1.article < t2.article
group by t1.article, t2.article