我正在使用SQL Server 2017,并且通过在此处询问许多问题,我发现了case
语句在SQL中充当if - else
。这很好,但不能满足我从结果集中获得的需求。如果我有一个销售表,其中包含金额,销售日期和项目说明。我正在尝试写这样的东西。
Select
sum(amount) -- total amount,
count(date_of_sale) -- number of days selling
sum(amount where date_of_sale between certain date and certain date)
我不想在其中放置where子句,因为我不希望它影响其他列的结果。我无法使用case
声明来解决这个问题
答案 0 :(得分:6)
我们可以在此处使用条件汇总,然后对CASE
表达式求和,该表达式仅包含您感兴趣的日期范围内的金额。
SELECT
SUM(amount) AS total_sales,
COUNT(date_of_sale) AS total_items,
SUM(CASE WHEN date_of_sale BETWEEN start_date AND end_date
THEN amount ELSE 0 END) AS partial_sales,
COUNT(CASE WHEN date_of_sale BETWEEN start_date AND end_date
THEN 1 END) AS partial_items
FROM yourTable;