如何根据别名列

时间:2016-08-01 14:39:45

标签: sql-server tsql

我正在编写查询以返回事件的预订数据表。我已使用SUM汇总对每日预订的数量进行分组。我现在想创建一个累计运行总计的列。

我无法让我的查询起作用,因为(我假设)它不喜欢别名列标题包含在聚合函数中。

请有人可以告诉我最好的方法吗?

SELECT
    'Recruitment Event' Event,
    CAST(ep.CREATIONDATE AS date) AS 'Date of Booking',
    SUM(CASE
        WHEN ep.CREATIONDATE IS NOT NULL THEN 1
        ELSE 0
    END) 'Total Bookings',
    (SELECT
        SUM('Total Bookings')
    FROM EVENTPLACE AS ep
    WHERE CAST(ep.CREATIONDATE AS date) <= CAST(ep.CREATIONDATE AS date))
    'Running Total'
FROM EVENTPLACE AS ep
LEFT JOIN EVENTMODULE AS em
    ON em.EVENTMODULENO = ep.EVENTMODULENO
WHERE em.EVENTMODULENO = '11111111-ABCD-1234-1234-1010101010'
GROUP BY CAST(ep.CREATIONDATE AS date)
ORDER BY CAST(ep.CREATIONDATE AS date) DESC

3 个答案:

答案 0 :(得分:0)

由于这些行,你收到错误..

SUM (case when ep.CREATIONDATE IS NOT NULL then 1 else 0 end) 'Total Bookings',
(SELECT SUM ('Total Bookings') FROM EVENTPLACE 

您正在尝试选择在同一阶段定义的别名,并且您将其作为字符串传递。您的查询将无法正常工作,除非您将其与主表格相关联,但您没有这样做。

以下查询适用于SQLServer 2012

;with cte
as
(
SELECT 'Recruitment Event' Event,
cast(ep.CREATIONDATE as date) as 'Date of Booking',
SUM (case when ep.CREATIONDATE IS NOT NULL then 1 else 0 end) 'Total Bookings',
FROM EVENTPLACE as ep
LEFT JOIN EVENTMODULE as em ON em.EVENTMODULENO=ep.EVENTMODULENO
WHERE em.EVENTMODULENO = '11111111-ABCD-1234-1234-1010101010'
GROUP BY cast(ep.CREATIONDATE as date)
)
select *,
sum([Total Bookings]) 
over (order by [Date of Booking] ROWS UNBOUNDED  ECEDING ) as   'Runningtotal'
from 
 cte

答案 1 :(得分:0)

问题是你的select语句中有一个SUM()函数,但并不是所有其他列都包含在你的group by子句中。

解决方案是在SUM函数之后添加一个OVER(ORDER BY ...)子句来计算运行总数。

SELECT
    'Recruitment Event' Event,
    CAST(ep.CREATIONDATE AS date) AS 'Date of Booking',
    SUM(CASE
        WHEN ep.CREATIONDATE IS NOT NULL THEN 1
        ELSE 0
    END)OVER(ORDER BY CAST(ep.CREATIONDATE AS date) DESC)  'Running Total',
FROM EVENTPLACE AS ep
LEFT JOIN EVENTMODULE AS em
    ON em.EVENTMODULENO = ep.EVENTMODULENO
WHERE em.EVENTMODULENO = '11111111-ABCD-1234-1234-1010101010'
CAST(ep.CREATIONDATE AS date) DESC

答案 2 :(得分:0)

试试这个

SELECT  
    [Event]             = 'Recruitment Event' ,
    [Date of Booking]   = CAST(ep.CREATIONDATE AS DATE),
    [Total Bookings]    = COUNT(ep.CREATIONDATE),
    [Running Total]     = SUM(COUNT(ep.CREATIONDATE)) OVER (ORDER BY CAST(ep.CREATIONDATE AS DATE) DESC)
FROM    
    EVENTPLACE AS ep
WHERE   
    EXISTS (SELECT 
                * 
            FROM 
                EVENTMODULE em 
            WHERE 
                em.EVENTMODULENO = ep.EVENTMODULENO 
                AND em.EVENTMODULENO = '11111111-ABCD-1234-1234-1010101010')
GROUP BY 
    CAST(ep.CREATIONDATE AS DATE)
ORDER BY 
    CAST(ep.CREATIONDATE AS DATE) DESC

COUNT(ep.CREATIONDATE)将忽略与您的SUM(CASE)

结果相同的空值

您真的不必使用EXISTS,但您可能应该将LEFT JOIN更改为JOIN,因为您正在使用em.EVENTMODULENO WHERE 1}}陈述

SUM(COUNT(ep.CREATIONDATE)) OVER ()将为您提供总计数。您在ORDER BY中使用OVER来确定SUM的顺序。由于您按CAST(ep.CREATIONDATE AS DATE) DESC订购,因此您可以在OVER()

中使用该订单