如果所有客户都包含销售记录,则此查询已经有效。如果该客户没有订单明细记录,则该客户甚至不会出现在以下查询中返回的行集中。当发生这种情况时,我怎么能弥补零? 感谢
select c1.type0 AS type, NULLIF(c.cnt,0) AS cnt from
(select ct.CustomerTypeName AS type0 from customer_type ct) c1
LEFT JOIN
(select '贵宾会员' As type0, count(c.CustomerCode) AS cnt
from customer c INNER JOIN
(select c.CustomerCode, sum(od.NetSales) AS Sales from customer c
INNER JOIN orders o ON (c.CustomerCode = o.CustomerCode)
INNER JOIN order_details od ON (o.OrderCode = od.OrderCode),
VIPLevelUpParam v, ActiveParam a
where a.ActiveID = v.LevelUpID
AND a.TableName = 'VIPLevelUpParam'
AND TRIM(CAST(CAST(YEAR(c.MemoryDate) AS CHAR(4)) AS VARCHAR(4))) || '-' ||
TRIM(CAST(CAST(MONTH(c.MemoryDate) AS CHAR(2)) AS VARCHAR(2)))
= '2013-11'
group by c.CustomerCode, v.LevelUpAmount
having sum(od.NetSales) >= v.LevelUpAmount) c1
ON c.CustomerCode = c1.CustomerCode
union
select '普通会员' AS type0, count(c.CustomerCode) AS cnt
from customer c INNER JOIN
(select c.CustomerCode, sum(od.NetSales) AS Sales from customer c
INNER JOIN orders o ON (c.CustomerCode = o.CustomerCode)
INNER JOIN order_details od ON (o.OrderCode = od.OrderCode),
VIPLevelUpParam v, ActiveParam a
where a.ActiveID = v.LevelUpID
AND a.TableName = 'VIPLevelUpParam'
AND TRIM(CAST(CAST(YEAR(c.MemoryDate) AS CHAR(4)) AS VARCHAR(4))) || '-' ||
TRIM(CAST(CAST(MONTH(c.MemoryDate) AS CHAR(2)) AS VARCHAR(2)))
= '2013-11'
group by c.CustomerCode, v.LevelUpAmount
having sum(od.NetSales) < v.LevelUpAmount) c2
ON c.CustomerCode = c2.CustomerCode
) c
ON c.type0 = c1.type0
group by c1.type0, c.cnt;
答案 0 :(得分:0)
您似乎只需要使用LEFT JOIN
在代码片段中:
select c.CustomerCode, sum(od.NetSales) AS Sales from customer c
INNER JOIN orders o ON (c.CustomerCode = o.CustomerCode)
INNER JOIN order_details od ON (o.OrderCode = od.OrderCode)
尝试使用:
select c.CustomerCode, sum(od.NetSales) AS Sales from customer c
LEFT JOIN orders o ON (c.CustomerCode = o.CustomerCode)
INNER JOIN order_details od ON (o.OrderCode = od.OrderCode)