我有一个包含3列的销售表:date1(这是商店销售和在线销售的实际交易日期),date2(已在线下订单)和sales($)列,显示特定日期的总销售额(两者商店和在线)。如果商店中发生了销售,则date2将为null,因为商店只有一个日期,即date1。
date1 |date2 |sales
6/1/2015 ? 1000
6/1/2015 6/1/2015 2000
15/2/2015 10/2/2015 3000
16/3/2015 ? 5500
.
.
.
我在两个日期列上使用了case语句,以按日期返回一年的总销售额。
这是我的代码:
case when date2 is null then date1 else date2 end as purchase date,
sum(sale) as total_sales
where date1 between '2015/1/1' and '2015/12/31'
and date2 between '2015/1/1' and '2015/12/31'
group by 1
;
我的预期输出应该有365行,并且从'1 / 1'2015'开始每天的在线和商店销售总额相加,但是我得到了7000行。我应该对我的代码进行哪些更改?
答案 0 :(得分:2)
尝试一下:
SELECT Purchase_Date, SUM(sales) as Total_Sales
FROM (
SELECT coalesce(date2, date1) as Purchase_date, sales
FROM [MyTable]
) t
WHERE Purchase_Date > = '20150101' and Purchase_Date < '20160101'
GROUP BY Purchase_Date
注意我对日期所做的事情。不同的格式是ISO-8601不分隔格式,并且由于历史原因,它是在Sql Server中使用仅日期值时的最佳选择。 “完整的日期+时间”值应使用更熟悉的yyyy-MM-dd HH:mm:ss.fff
ISO-8601分隔格式。其他一些数据库没有相同的历史古怪,或者不喜欢其他格式,但是您在此处看到的内容仍然可以在任何地方使用。
我还使用了两个比较,而不是BETWEEN
,它们的上限实际上是第二天,具有排他边界而不是包含边界(<
,而不是<=
)。这是确保您获得所需的整个范围的最佳方法,而您却不需要。
或者我们可以重写此代码以不需要嵌套的SELECT。它甚至可能运行得更快...但是我们不得不重复COALESCE()
很多次:
SELECT coalesce(date2, date1) As Purchase_Date, SUM(sales) as Total_Sales
FROM [MyTable]
WHERE coalesce(date2, date1) > = '20150101' and coalesce(date2, date1) < '20160101'
GROUP BY coalesce(date2, date1)
答案 1 :(得分:1)
我认为正确的语法应该是,
select sum(sale) as total_sales,
case
when date2 is null then date1
else date2
end as purchase date
from table_name
where date1 between '2015/1/1' and '2015/12/31'
and
where date2 between '2015/1/1' and '2015/12/31'
group by sale;
关于日期的另一条注释,要在之间使用,您应该使用日期的字段数据类型,而不是varchare 像这样的日期还有另一个语法版本
where date2 between #2015/1/1# and #2015/12/31#
万一由于某种原因您不能使用引号