计数多列

时间:2018-12-11 23:10:07

标签: sql oracle

我有两个CTE。以下是我第一个CTE的输出。

| ORDER_NUMBER | ORDER_FLAG | EMPLOYEE | PRODUCT_CATEGORY | SALES  |
|--------------|------------|----------|------------------|--------|
| 3158132      | 1          | Don      | Newpaper Ad      | 16.00  |
| 3158132      | 1          | Don      | Magazine Ad      | 15.00  |
| 3158132      | 0          | Don      | TV Ad            | 0.00   |
| 3158132      | 1          | Don      | Billboard Ad     | 56.00  |
| 3006152      | 1          | Roger    | TV Ad            | 20.00  |
| 3006152      | 0          | Roger    | Magazine Ad      | 0.00   |
| 3006152      | 1          | Roger    | Newspaper Ad     | 214.00 |
| 3012681      | 1          | Ken      | TV Ad            | 130.00 |
| 3012681      | 0          | Ken      | Magazine Ad      | 0.00   |
| 9818123      | 1          | Pete     | Billboard Ad     | 200.00 |

我正在尝试按员工计算不同的订单号和销售额。顺序标志将为10。如果销售量大于0.00,则订单标志将设置为1

我想要的输出。

| Employee | Sales  | Orders |
|----------|--------|--------|
| Don      | 87.00  | 1      |
| Ken      | 130.00 | 1      |
| Pete     | 200.00 | 1      |
| Roger    | 234.00 | 1      |

我试图将不同的,大小写的和连续的语句组合在一起,但没有任何运气。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您可以使用此:

with cteTotalSales (...) as ()
select employee, 
   case when (sum(sales)) > 0 
     then 1 else 0 as Orders, 
 sum(sales)
from cteTotalSales
group by employee

答案 1 :(得分:0)

这应该很简单:

with cte as (...)
select 
    employee, 
    sum(sales),
    count(distinct order_number)
from cte 
group by employee

答案 2 :(得分:0)

此查询将为您服务

SELECT 
  EMPLOYEE,
  SUM(SALES) SALES,
  1 AS ORDERS
FROM 
  YOUR_TABLE
GROUP BY 
  EMPLOYEE

您可以将您的子查询替换为YOUR_TABLE。

SELECT 
  EMPLOYEE,
  SUM(SALES) SALES,
  1 AS ORDERS
FROM 
(
  SELECT * FROM ...
)
GROUP BY 
  EMPLOYEE