0
USE [MAS_CAN]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spHistorybyCalenderYear]--create a stored proc
@Year int = '2013'
AS
Begin
SET NOCOUNT ON
SELECT 
isnull(round(l.UnitPrice*l.QuantityShipped,2),0) as SalesAmount,
isnull(round(l.unitCost*l.QuantityShipped,2),0) as CostAmount,
(case 
when month(h.INVOICEDATE)=01 then '01'
when month(h.INVOICEDATE)=02 then '02'
when month(h.INVOICEDATE)=03 then '03'
when month(h.INVOICEDATE)=04 then '04'
when month(h.INVOICEDATE)=05 then '05'
when month(h.INVOICEDATE)=06 then '06'
when month(h.INVOICEDATE)=07 then '07'
when month(h.INVOICEDATE)=08 then '08'
when month(h.INVOICEDATE)=09 then '09'
when month(h.INVOICEDATE)=10 then '10'
when month(h.INVOICEDATE)=11 then '11'
when month(h.INVOICEDATE)=12 then '12'
END) as Period
FROM AR_INVOICEHISTORYHEADER h join AR_INVOICEHISTORYDETAIL l on (h.INVOICENO = l.INVOICENO)
Group by l.unitprice,l.unitcost,l.quantityShipped,h.invoicedate
order by Period
END 

我想按期间分组...说我想看看

Period SalesAmount  CostAmount
01     22           19
02     24           25
4

1 回答 1

1

用这个:

GROUP BY l.unitprice, l.unitcost, l.quantityShipped, CAST(MONTH(h.invoicedate) as varchar)

此外,如果你在它的位置使用它,你可以摆脱那个大的 case 语句:

SELECT 
isnull(round(l.UnitPrice*l.QuantityShipped,2),0) as SalesAmount,
isnull(round(l.unitCost*l.QuantityShipped,2),0) as CostAmount,
CAST(MONTH(h.invoicedate) as varchar) as Period
FROM ...

正如@Kaf 提到的,如果你想Period0填充,你可以使用其中任何一个而不是直接CAST

right(100 + month(h.invoicedate),2)
left(convert(varchar, h.invoicedate, 10), 2)
于 2013-03-13T15:27:12.207 回答