SQL Server查询组的日期和金额

时间:2019-04-03 13:40:44

标签: sql sql-server

我有这张桌子:

ID, PayDate  , ActualPayDate , Cost , Price
1 , 18-11-18 , 30-11-18      , 100  , 120
2 , 28-3-19  , 1-4-19        , 150  , 230
3 , 5-4-19   , null          , 170  , 290
4 , 5-3-19   , null          , 100  , 200

我想按年份和月份将“费用”列的PayDate分组,并按“价格”的“ ActualPayDate”分组,结果应该像这样:

Year , Month , Cost , Price
2018 , 11    , 100  , 120
2018 , 12    , 0    , 0
2019 , 1     , 0    , 0
2019 , 2     , 0    , 0
2019 , 3     , 250  , 0
2019 , 4     , 170  , 230

请帮助。

2 个答案:

答案 0 :(得分:1)

使用apply

select year(v.dte), month(v.dte), coalesce(sum(v.cost), 0) as cost,
      coalesce(sum(v.price)) as price
from t cross apply
     (values (t.paydate, t.cost, 0), 
             (t.actualpaydate, 0, t.price)
     ) v(dte, cost, price)
group by year(v.dte), month(v.dte)
order by year(v.dte), month(v.dte);

答案 1 :(得分:0)

请尝试使用此子sql,然后加入时间缩减。

with CTE as 
(
select Year(PayDate) as [Year] 
    , Month(PayDate) as [Month]
    , Sum(Cost) as [cost] 
    , Sum(Price) as Price
from table
Group by Year(PayDate), Month(PayDate)
)
Select Cte.*,  tblDimTime * from CTE 
Outer join tblDimTime
 on cte.[Year] = cte.[Year]
 and cte.[Month] = cte.[Month]

这是“在SQL Server中创建日期维度或日历表”的链接

https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/