我有一个SQL表“ITM_SLS”,其中包含以下字段:
ITEM
DESCRIPTION
TRANSACTION #
DATE
QTY SOLD
我希望能够输出QTY SOLD一个月的值和一年的日期值,以便输出看起来像这样:
ITEM, DESCRIPTION, QTY SOLD MONTH, QTY SOLD YEAR TO DATE
这可能吗?
答案 0 :(得分:1)
您可以使用子查询中的group by
计算销售总量。例如
select a.Item, a.Description, b.MonthQty, c.YearQty
from (
select distinct Item, Description from TheTable
) a
left join (
select Item, sum(Qty) as MonthQty
from TheTable
where datediff(m,Date,getdate()) <= 1
group by Item
) b on a.Item = b.Item
left join (
select Item, sum(Qty) as YearQty
from TheTable
where datediff(y,Date,getdate()) <= 1
group by Item
) c on a.Item = c.Item
将子查询限制为特定日期范围的方法因DBMS而异,此示例使用SQL Server datediff
函数。
答案 1 :(得分:1)
假设“一个月”是上个月......
select item
, description
, sum (case when trunc(transaction_date, 'MM')
= trunc(add_months(sysdate, -1), 'MM')
then qty_sold
else 0
end) as sold_month
, sum(qty_sold) as sold_ytd
from itm_sls
where transaction_date >= trunc(sysdate, 'yyyy')
group by item, description
/
答案 2 :(得分:0)
这将让您了解自己可以做些什么:
select
ITEM,
DESCRIPTION,
QTY SOLD as MONTH,
( select sum(QTY SOLD)
from ITM_SLS
where ITEM = I.ITEM
AND YEAR = i.YEAR
) as YEAR TO DATE
from ITM_SLS I