如何使用单个查询从一个表中基于两种不同条件获得多个结果

时间:2018-07-12 11:22:18

标签: sql oracle

我有一张表格,其中列出了每天的销售数量和相关的销售金额。以下是表SalesMaster。

Date     Item Sales Amount
30062018 1    5     50000
30062018 2    5     50000
30062018 3    5     50000
30062018 4    5     50000
30062018 5    5     50000
30062018 6    5     50000
30062018 7    5     50000
31052018 1    5     50000
31052018 2    5     50000
31052018 3    5     50000
31052018 4    5     50000
31052018 5    5     50000
31052018 6    5     50000

我要从此表中获得以下结果。我想列出每个月底每个商品的销售数量,如下所示。

Item May_Sales June_Sales
1    5000      5000
2    5000      5000
3    5000      5000
4    5000      5000
5    5000      5000
6    5000      5000
7    5000      5000

以下是我编写的代码,但它说:[1]:ORA-01427:单行子查询返回多个行。

SELECT t1.item,
       sales AS may_sales,
       (SELECT sales
          FROM salesmaster t1
         WHERE t1.date = '30-June-2018')
           AS june_sales
  FROM salesmaster t1
 WHERE t1.date = '31-May-2018'

3 个答案:

答案 0 :(得分:0)

我只会使用条件聚合:

SELECT sm.item,
       SUM(CASE WHEN t1.date = '31052018' then sales END) as may_sales,
       SUM(CASE WHEN t1.date = '30062018' then sales END) as june_sales
FROM salesmaster sm
GROUP BY sm.item
ORDER BY sm.item;

您的第一列看起来并不像日期,因此不要在其上使用日期比较。如果是日期,请使用:

SELECT sm.item,
       SUM(CASE WHEN t1.date = DATE '2018-05-31' THEN sales END) as may_sales,
       SUM(CASE WHEN t1.date = DATE '2018-06-30' THEN sales END) as june_sales
FROM salesmaster sm
GROUP BY sm.item
ORDER BY sm.item;

对于您的查询,它在子查询中的item上缺少相关子句。

编辑:

如果要区别,则需要重复这些表达式。这是一种方法:

SELECT sm.item,
       SUM(CASE WHEN t1.date = '31052018' THEN sales END) as may_sales,
       SUM(CASE WHEN t1.date = '30062018' THEN sales END) as june_sales,
       SUM(CASE WHEN t1.date = '31052018' THEN -sales) 
                WHEN t1.date = '30062018' THEN sales
           END) as diff,

答案 1 :(得分:0)

对于要获得的结果,条件聚合将是最佳方法:

select 
  item,  
  sum(case when to_date(Date, 'DDMMYYYY') between to_date('01052018','YYYYMMDD') and to_date('31052018','DDMMYYYY') then Amount else 0 end) may_sales, 
  sum(case when to_date(Date, 'DDMMYYYY') between to_date('01062018','YYYYMMDD') and to_date('31062018','DDMMYYYY') then Amount else 0 end) june_sales
from SalesMaster
group by item
order by item;

您必须将“日期”字段转换为有效字段以获取每月总计。

答案 2 :(得分:0)

select item, may.sales as MAY_sales, JUNE.sales as JUNE_sales  from
(SELECT distinct item
FROM salesmaster )MAST  
left join 
(SELECT item , sales
FROM salesmaster 
WHERE date = '31052018') MAY
on (MAST.item = JUNE.item)
left join 
(SELECT item , sales
FROM salesmaster 
WHERE date = '31052018') JUNE
on (MAST.item = JUNE.item)