我有以下查询来显示某段时间内的销售情况,但不幸的是,它似乎没有报告在其他类别中购买过的客户。
例如,客户之前从未购买过产品(第2只或第3只猫),并且第一次购买5/5的产品。该报告没有出现在报告上,因为他们之前从cat 60购买了一些东西。
select CUSTOMER_DEL_HIST.CUSTOMER_NUMBER
,max ( CUSTOMER_DEL_HIST.SERVE_LOCATION) as SERVE_LOCATION
,max ( CUSTOMER_DEL_HIST.PRODUCT_NUMBER) as PRODUCT_NUMBER
,max ( CUSTOMER_DEL_HIST.DEL_DATE) as DEL_DATE
,max ( ORDER_RTE_BAL.WAREHOUSE) as WAREHOUSE
,max ( ORDER_RTE_BAL.ROUTE_NUMBER) as ROUTE_NUMBER
,max ( ORDER_RTE_BAL.ROUTE_DAY) as ROUTE_DAY
from CUSTOMER_DEL_HIST
inner join INV_MASTER on CUSTOMER_DEL_HIST.PRODUCT_NUMBER = INV_MASTER.PRODUCT_NUMBER
inner join ORDER_HEADER on CUSTOMER_DEL_HIST.ORDER_NUMBER = ORDER_HEADER.ORDER_NUMBER
inner join ORDER_RTE_BAL
on ORDER_HEADER.WAREHOUSE_NUMBER = ORDER_RTE_BAL.WAREHOUSE
and ORDER_HEADER.ROUTE_NUMBER = ORDER_RTE_BAL.ROUTE_NUMBER
and ORDER_HEADER.ROUTE_DAY = ORDER_RTE_BAL.ROUTE_DAY
and ORDER_HEADER.DELIVERY_DATE = ORDER_RTE_BAL.ROUTE_DATE
where (CUSTOMER_DEL_HIST.DEL_DATE between X and Y)
and (INV_MASTER.INVENTORY_CATEGORY in ('02', '03', '60', '74'))
and (CUSTOMER_DEL_HIST.CUSTOMER_NUMBER not in
(select H2.CUSTOMER_NUMBER
from CUSTOMER_DEL_HIST H2
inner join INV_MASTER as I on H2.PRODUCT_NUMBER = I.PRODUCT_NUMBER
where H2.DEL_DATE between '6/01/2014' and '04/30/2015'
and I.INVENTORY_CATEGORY in ('02', '03', '60', '74')))
group by CUSTOMER_DEL_HIST.CUSTOMER_NUMBER
我是SQL的新手但知道我应该在SELECT中使用union,但这就是它。不幸的是,我不够精通,所以我正在寻找一些帮助,以便我如何获得我想要的结果。
答案 0 :(得分:1)
无法提供太多帮助解决实际问题的方法,但既然你说你是新手,我想我会告诉你,只需要一点点努力,你的查询就会更清晰。如果你开始使用别名,你可以消除每行数十个字符,你的代码可以更清洁。许多格式是个人偏好,但您发布的代码只是挑战阅读的方式。这是一种利用别名并大大清理它的方法。
SELECT cdh.customer_number
, Max(cdh.serve_location) AS serve_location
, Max(cdh.product_number) AS product_number
, Max(cdh.del_date) AS del_date
, Max(orb.warehouse) AS warehouse
, Max(orb.route_number) AS route_number
, Max(orb.route_day) AS route_day
FROM customer_del_hist cdh
INNER JOIN inv_master im ON cdh.product_number = im.product_number
INNER JOIN order_header oh ON cdh.order_number = oh.order_number
INNER JOIN order_rte_bal orb ON oh.warehouse_number = orb.warehouse
AND oh.route_number = orb.route_number
AND oh.route_day = orb.route_day
AND oh.delivery_date = orb.route_date
WHERE cdh.del_date BETWEEN @StartDate AND @EndDate
AND im.inventory_category IN ('02', '03', '60', '74')
AND cdh.customer_number NOT IN
(
SELECT h2.customer_number
FROM customer_del_hist AS h2
INNER JOIN inv_master AS i ON h2.product_number = i.product_number
WHERE h2.del_date BETWEEN '6/01/2014' AND '04/30/2015'
AND i.inventory_category IN ('02', '03', '60', '74')
)
GROUP BY cdh.customer_number
答案 1 :(得分:1)
在查询的where子句中,最后一个部分有
cdh.customer_number NOT IN
(
SELECT h2.customer_number
FROM customer_del_hist AS h2
INNER JOIN inv_master AS i ON h2.product_number = i.product_number
WHERE h2.del_date BETWEEN '6/01/2014' AND '04/30/2015'
AND i.inventory_category IN ('02', '03', '60', '74')
)
这将是排除客户的区域。您可以看到子查询有一个where子句,并且此where子句指定inventory_category必须是02,03,60,74中的一个。因此,您找到所有购买任何一个类别中任何一个的客户,然后将它们从主查询的结果中排除。