比较两列中两个不同日期范围的销售额

时间:2018-12-24 07:23:33

标签: sql sql-server postgresql sqlite tsql

我想在两列中比较两个不同日期范围的销售额。.我在下面使用查询,但给出了错误的销售额..请更正我的查询

select s1.Itm_cd,s1.Itm_Name,Sum(S1.amount),Sum(s2.amount) 
from salestrans s1,salestrans s2 
where s1.Itm_cd = S2.Itm_cd 
and S1.Tran_dt between '20181101' and'20181130'
and S2.Tran_dt between '20171101' and '20171130' 
group by s1.Itm_cd,s1.Itm_Name 
Order by s1.Itm_cd

2 个答案:

答案 0 :(得分:0)

我怀疑您要在此处进行条件聚合:

WITH cte AS (
    SELECT
        s1.Itm_cd,
        s1.Itm_Name,
        SUM(CASE WHEN s1.Tran_dt BETWEEN '20181101' AND '20181130'
                 THEN s1.amount ELSE 0 END) AS sum_2018,
        SUM(CASE WHEN s1.Tran_dt BETWEEN '20171101' AND '20171130'
                 THEN s1.amount ELSE 0 END) AS sum_2017
    FROM salestrans s1
    GROUP BY
        s1.Itm_cd,
        s1.Itm_Name
)

SELECT
    Itm_cd,
    Itm_Name,
    sum_2018,
    sum_2017,
    CASE WHEN COALESCE(sum_2017, 0) <> 0
         THEN FORMAT(100.0 * (sum_2018 - sum_2017) / sum_2017, 'N', 'en-us')
         ELSE 'NA' END AS growth_pct
FROM cte
ORDER BY
    Itm_cd;

答案 1 :(得分:0)

请尝试以下

select s1.Itm_cd,s1.Itm_Name,Sum(S1.amount),Sum(s2.amount) 
from salestrans s1,salestrans s2 
where s1.Itm_cd = S2.Itm_cd 
and Convert(Varchar(10),S1.Tran_dt,112) between '20181101' and'20181130'
and  Convert(Varchar(10),S2.Tran_dt,112) between '20171101' and '20171130' 
group by s1.Itm_cd,s1.Itm_Name 
Order by s1.Itm_cd

这里的逻辑是,在进行比较时,右侧仅提供日期,不提供任何分隔符和时间。应该对左侧的列进行相同的比较。

if(Convert(Varchar(10), getdate(),112) = '20181224')
  print 'Matched'
else
  print 'Not Matched'

if(getdate() = '20181224')
   print 'Matched'
else
  print 'Not Matched'

在这里,输出首先是Matched,而输出是Not Matched,因为在第一种情况下,采用了双方相同的格式进行比较。