查询中的动态别名

时间:2012-11-27 05:19:59

标签: sql

我有一个场景,用户输入一个月,输出是该月的销售,然后是下一个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是来自用户的输入月我希望别名也动态更改,以便如何操作列别名任何帮助 感谢名单

1 个答案:

答案 0 :(得分:0)

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

在以下文章的帮助下:t-sql select get all Months within 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)