sql:基于计算列的分组?

时间:2012-08-28 12:24:21

标签: sql-server tsql select group-by

我有这些数据显示按年份分组的综合报告。我用的很简单 GROUP BY YEAR(BookingDate)条款,一切正常。但我想要的是财政年度的那一年(1 April31 May)而不是正常的日历年,那我该怎么做呢?查询是..

SELECT 
    CONVERT(VARCHAR(25), c.Duration) AS Duration, 
    COALESCE(c.totalbookings, 0) AS totalbookings
FROM
    (SELECT 
               YEAR(bookingdate) AS Duration, 
               COUNT(*) AS totalbookings 
           FROM 
               entbookings
            WHERE BranchId=@Branchid
           GROUP BY YEAR(bookingdate)
    ) AS c 
LEFT OUTER JOIN 
    (SELECT 
               Duration, 
               SUM(totalitems) 'bkdqty'
           FROM 
               [yrItemWISeTotalQty] (@BranchId) AS BkdQty
           GROUP BY Duration
    ) AS d 
ON c.Duration = d.Duration

yrItemWISeTotalQty定义为

CREATE FUNCTION [dbo].[yrItemWiseTotalQty]
(
@BrachId VARCHAR(MAX)
) 

RETURNS TABLE AS
    RETURN
SELECT 
    YEAR(EntBookings.BookingDate) AS Duration, 
    Sum(dbo.EntBookings.ItemCost) AS totalcost,
WHERE   EntBookings.BranchId = @BrachId
GROUP BY Year(EntBookings.BookingDate)

同样,我正在使用GROUP BY Year()来完成这项工作,但是我需要对其进行修改以便采取fy即(4月1日至3月31日)。我该怎么办?

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
    case when month(EntBookings.BookingDate) <4
         then YEAR(EntBookings.BookingDate)-1
         else YEAR(EntBookings.BookingDate) end  AS Duration, 
    Sum(dbo.EntBookings.ItemCost) AS totalcost
WHERE   EntBookings.BranchId = @BrachId
GROUP BY case when month(EntBookings.BookingDate) <4 
         then YEAR(EntBookings.BookingDate)-1 
         else YEAR(EntBookings.BookingDate) end as [year]

答案 1 :(得分:0)

定义SQL函数
getFinancialYear(Data[TimeStamp] )
返回财务年份编号并使用该编号按和 即。

...
GROUP BY getFinancialYear(BookingDate)
...