7 杂志
TITLES
PRODUCT_ID INTEGER 产品号
MAGAZINE_SKU INTEGER 杂志编号
ISSN INTEGER 国际期刊号
ISSN_YEAR INTEGER 日期
NEWSSTANDS
STAND_NBR INTEGER 报亭编号
STAND_NAME VARCHAR2(20) 姓名
SALES
PRODUCT_ID INTEGER 产品号
STAND_NBR INTEGER 报亭编号
NET_SOLD_QTY INTEGER 平均销售数量
每个表的数据如下
TITLES
PRODUCT_ID MAGAZINE_SKU ISSN ISSN_YEAR
1 12345 1 2006
2 2667 1 2006
3 48632 1 2006
4 1107 1 2006
5 12345 2 2006
6 2667 2 2006
7 48632 2 2006
8 1107 2 2006
SALES
PRODUCT_ID STAND_NBR NET_SOLD_QTY
1 1 1
2 1 4
3 1 1
4 1 1
5 1 1
6 1 2
7 1 1
4 2 5
8 2 6
3 2 1
1 3 1
2 3 3
4 3 1
5 3 1
6 3 3
7 3 3
1 4 1
2 4 1
3 4 4
4 4 1
5 4 1
6 4 1
7 4 2
--先得到各个每个报亭各个杂志的平均销售数量
SELECT STAND_NBR,
AVG(CASE
WHEN MAGAZINE_SKU = 2667 THEN
NET_SOLD_QTY
END) AVG_2667,
AVG(CASE
WHEN MAGAZINE_SKU = 48632 THEN
NET_SOLD_QTY
END) AVG_48632,
AVG(CASE
WHEN MAGAZINE_SKU = 1107 THEN
NET_SOLD_QTY
END) AVG_1107
FROM SALES, TITLES
WHERE SALES.PRODUCT_ID = TITLES.PRODUCT_ID
GROUP BY STAND_NBR
STAND_NBR AVG_2667 AVG_48632 AVG_1107
1 3 1 1
2 1 5.5
4 1 3 1
3 3 3 1
然后在按照条件筛选
SELECT STAND_NBR
FROM (SELECT STAND_NBR,
AVG(CASE
WHEN MAGAZINE_SKU = 2667 THEN
NET_SOLD_QTY
END) AVG_2667,
AVG(CASE
WHEN MAGAZINE_SKU = 48632 THEN
NET_SOLD_QTY
END) AVG_48632,
AVG(CASE
WHEN MAGAZINE_SKU = 1107 THEN
NET_SOLD_QTY
END) AVG_1107
FROM SALES, TITLES
WHERE SALES.PRODUCT_ID = TITLES.PRODUCT_ID
GROUP BY STAND_NBR)
WHERE AVG_1107 > 5
OR (AVG_2667 > 2 AND AVG_48632 > 2)
最终结果为
STAND_NBR
2
3