大家好
在T-SQL中,如果想將二段CASE的結果串聯起來的話,應該如何處理?我的T-SQL如下:
SELECT 'YR'=CASE
WHEN SUBSTRING(CONVERT(NVARCHAR(8),DocDate,112),5,2) > 10
THEN (SUBSTRING(CONVERT(NVARCHAR(8),DocDate,112),1,4)-1911)+1
ELSE SUBSTRING(CONVERT(NVARCHAR(8),DocDate,112),1,4)-1911
END,
'Mon'=CASE
WHEN SUBSTRING(CONVERT(NVARCHAR(8),DocDate,112),5,2) = 01 THEN '03'
WHEN SUBSTRING(CONVERT(NVARCHAR(8),DocDate,112),5,2) = 02 THEN '03'
WHEN SUBSTRING(CONVERT(NVARCHAR(8),DocDate,112),5,2) = 03 THEN '05'
WHEN SUBSTRING(CONVERT(NVARCHAR(8),DocDate,112),5,2) = 04 THEN '05'
WHEN SUBSTRING(CONVERT(NVARCHAR(8),DocDate,112),5,2) = 05 THEN '07'
WHEN SUBSTRING(CONVERT(NVARCHAR(8),DocDate,112),5,2) = 06 THEN '07'
WHEN SUBSTRING(CONVERT(NVARCHAR(8),DocDate,112),5,2) = 07 THEN '09'
WHEN SUBSTRING(CONVERT(NVARCHAR(8),DocDate,112),5,2) = 08 THEN '09'
WHEN SUBSTRING(CONVERT(NVARCHAR(8),DocDate,112),5,2) = 09 THEN '11'
WHEN SUBSTRING(CONVERT(NVARCHAR(8),DocDate,112),5,2) = 10 THEN '11'
WHEN SUBSTRING(CONVERT(NVARCHAR(8),DocDate,112),5,2) = 11 THEN '01'
WHEN SUBSTRING(CONVERT(NVARCHAR(8),DocDate,112),5,2) = 12 THEN '01'
END
FROM dbo.OINV
謝謝!!
在測試環境模擬的SQL, 自行參考修改一下囉...
<pre class="c" name="code">
select a.SL_DATE,
"YM"=CASE when a.YM_NUM%2=0 then YM_NUM-1 else YM_NUM end ,COUNT(1) 交易數
from (
select top 10000
SL_DATE,CAST(CONVERT(varchar(6),DATEADD(MONTH,2,
CONVERT(smalldatetime,SL_DATE,112)),112) as int)-191100 YM_NUM
FROM dbo.SALE_H
where SL_DATE like '2008%' ) a
group by a.SL_DATE,CASE when a.YM_NUM%2=0 then YM_NUM-1 else YM_NUM end