我正在尝试使用子查询来查询我们的订单数据库并返回3列,例如:
Date Orders Replacements
09-MAY-14 100 5
... ... ...
创建的每个订单都有一个理由,这基本上意味着它是一个替代产品,即没有理由的订单是新订单,有理由的订单是替换订单。
我正在使用下面的查询来尝试获取此信息,但是我收到了很多错误消息,每次我认为我修复了一个我创建了另外10个,所以假设我完全有错误的想法这里。
SELECT Orders.EntryDate AS "Date", COUNT(Orders.OrderNo) AS "Orders",
(SELECT COUNT(Orders.OrderNo) AS "Replacements"
FROM Orders
WHERE Orders.Reason IS NOT NULL
AND Orders.EntryDate = '09-MAY-2014'
AND Orders.CustomerNo = 'A001'
GROUP BY Orders.EntryDate
)
FROM Orders
WHERE Orders.Reason IS NULL
AND Orders.EntryDate = '09-MAY-2014'
AND Orders.CustomerNo = 'A001'
GROUP BY Orders.EntryDate
;
答案 0 :(得分:1)
为什么子查询使用大小写!
SELECT Orders.EntryDate AS "Date", COUNT(Orders.OrderNo) AS "Orders",
sum(CASE WHEN Orders.reason is null then 1 else 0 end) as "Replacements"
FROM Orders
WHERE Orders.Reason IS NULL
AND Orders.EntryDate = '09-MAY-2014'
AND Orders.CustomerNo = 'A001'
GROUP BY Orders.EntryDate
子查询必须每次执行,因为您需要评估案例可以为您执行的每条记录,然后对结果求和。如果您需要计算一些非替换订单,那么只需执行不同的情况而不是计数。
答案 1 :(得分:0)
您的错误可能是由于您未在子group by子句中包含子查询。您可以尝试这种方法,但这个方法更简单:
select entrydate "date"
, count(orderno) "orders"
, sum(case when reason is not null then 1 else 0 end) "replacements"
etc
group by entrydate
答案 2 :(得分:0)
您可以将case
表达式加起来,而不是使用另一个子查询和另一个where
子句:
SELECT Orders.EntryDate AS "Date",
SUM (CASE WHEN Orders.Reason IS NULL THEN 1 ELSE 0 END) AS "Orders",
SUM (CASE WHEN Orders.Reason IS NOT NULL THEN 1 ELSE 0 END) AS "Replacements"
FROM Orders
WHERE Orders.EntryDate = '09-MAY-2014'
AND Orders.CustomerNo = 'A001'
GROUP BY Orders.EntryDate
答案 3 :(得分:0)
这是你想要做的吗?
SELECT Orders.EntryDate
, COUNT(case when Orders.reason is null then 1 end) AS orders
, COUNT(case when Orders.reason is not null then 1 end) AS Replacements
FROM Orders
WHERE Orders.EntryDate = '09-MAY-2014'
AND Orders.CustomerNo = 'A001'
GROUP BY Orders.EntryDate
Replacements表达式可以简化为:
COUNT(Orders.reason)