2

我有这样的场景,用户输入一个月,输出是那个月的销售额,然后是接下来 12 个月的销售额,我也写了这个查询

select 
sum(decode(month ,to_char(add_months(to_date(&m,'mon'),0),'mon'), sales))   "&m" ,
sum(decode(month ,to_char(add_months(to_date(&m,'mon'),1),'mon'), sales))   "&m" ,
sum(decode(month ,to_char(add_months(to_date(&m,'mon'),2),'mon'), sales))   "&m" ,
sum(decode(month ,to_char(add_months(to_date(&m,'mon'),3),'mon'), sales))   "&m" ,
sum(decode(month ,to_char(add_months(to_date(&m,'mon'),4),'mon'), sales))   "&m" ,
sum(decode(month ,to_char(add_months(to_date(&m,'mon'),5),'mon'), sales))   "&m" ,
sum(decode(month ,to_char(add_months(to_date(&m,'mon'),6),'mon'), sales))   "&m" ,
sum(decode(month ,to_char(add_months(to_date(&m,'mon'),7),'mon'), sales))   "&m" ,
sum(decode(month ,to_char(add_months(to_date(&m,'mon'),8),'mon'), sales))   "&m" ,
sum(decode(month ,to_char(add_months(to_date(&m,'mon'),9),'mon'), sales))   "&m" ,
sum(decode(month ,to_char(add_months(to_date(&m,'mon'),10),'mon'), sales))  "&m" ,
sum(decode(month ,to_char(add_months(to_date(&m,'mon'),11),'mon'), sales))  "&m" ,
sum(decode(month ,to_char(add_months(to_date(&m,'mon'),12),'mon'), sales))  "&m" 
from sales

m是用户输入月份我希望别名也动态变化所以如何操作列别名任何帮助thanx

4

1 回答 1

0

看起来您使用的不是 MS SQL,但这在概念上可能会有所帮助

借助以下文章:t-sql select get all Months in a range of years

DECLARE @StartDate DATETIME,
        @EndDate   DATETIME,
        @Sql VARCHAR(max)
SELECT @StartDate = '2012-01-01',
        @EndDate   = '2012-12-01',
        @Sql = 'select'

;WITH
cteDates AS
(
    SELECT TOP (DATEDIFF(mm,@StartDate,@EndDate) + 1)
            MonthDate = DATEADD(mm,DATEDIFF(mm,0,@StartDate) + (ROW_NUMBER() OVER
                (ORDER BY (SELECT NULL)) -1),0)
    FROM sys.all_columns ac1
    CROSS JOIN sys.all_columns ac2
)

SELECT @SQL = @Sql + '
sum(decode(month ,to_char(add_months(to_date(''' +  DateName(month, MonthDate)  + ''',''mon''),' + CAST(MONTH(MonthDate) AS VARCHAR) + '),''mon''), sales))   "' + DateName(month, MonthDate) + '" ,'
FROM cteDates


SELECT @Sql = SUBSTRING(@Sql, 0, LEN(@Sql) -1) + '
from sales'
print @Sql

EXEC(@Sql)
于 2012-11-27T06:30:56.513 回答