2013-03-13 103 views
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 

我想这组通过一段...说我想看看请帮我group by子句

Period SalesAmount CostAmount 
01  22   19 
02  24   25 

回答

1

使用此:

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

而且,你可以摆脱那个大案例陈述,如果你使用它在这个地方:

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) 
+0

你可以使用'权(100 +月(h.invoicedate),2)期间'得到'前面0' – Kaf 2013-03-13 15:34:21

+0

@Kaf:好点,我错过了。更新 – PinnyM 2013-03-13 15:45:42