获取最后一行SQL Server 2008中的营业额总和

时间:2017-12-15 15:49:01

标签: sql-server sql-server-2008

解决方案:我必须在WHERE次查询中添加SELECT子句。

我正在研究SQL Server 2008数据库。

我正在尝试编写一个SQL查询来返回类似的结果集:

    date     | turnover_centrale    | turnover_public       
+------------+----------------------+--------------------
| 2017-02-14 | 233.34               | 383.83                    
| 2017-03-14 | 142.81               | 166.8                  
| 2017-04-14 | 173.25               | 250.51                
| 2017-05-14 | 186.96               | 245.08                
| 2017-06-14 | 61.26                | 97.67                 
| 2017-07-14 | 262.98               | 356.16                
| 2017-08-14 | 89.88                | 162.38               
| 2017-09-14 | 250.32               | 381.47                
| 2017-10-14 | 386.06               | 581.96                
| Total      | Result of the column | Result of the column

我的SQL查询是:

SELECT 
    CLC_DATE, CLC_PRIX_CENTRALE, CLC_PRIX_PUBLIC 
FROM 
    ##.dbo.CLIENTS_CONSO
WHERE 
    CF_USER = :ref

UNION ALL

SELECT 
    NULL, SUM(CLC_PRIX_CENTRALE), SUM(CLC_PRIX_PUBLIC) 
FROM 
    ##.dbo.CLIENTS_CONSO

遗憾的是,最后一行的结果是错误的:(

那么你有更好的解决方案吗?

非常感谢!

2 个答案:

答案 0 :(得分:0)

考虑到每个日期只有一个条目,可能是:

WITH VTE AS (
    SELECT CONVERT(date,[date]) AS [date], turnover_centrale, turnover_public
    FROM (VALUES 
                ('20170214',233.34,383.83),                    
                ('20170314',142.81,166.8 ),                 
                ('20170414',173.25,250.51),                
                ('20170514',186.96,245.08),                
                ('20170614',61.26 ,97.67 ),                
                ('20170714',262.98,356.16),                
                ('20170814',89.88 ,162.38),               
                ('20170914',250.32,381.47),                
                ('20171014',386.06,581.96)) V([date],turnover_centrale, turnover_public))
SELECT ISNULL(CONVERT(varchar(10),[date],120),'Total') AS [date],
       SUM(turnover_centrale) AS turnover_centrale,
       SUM(turnover_public) AS turnover_public
FROM VTE
GROUP BY [date] WITH ROLLUP;       

答案 1 :(得分:0)

非常感谢! 我的表是这样构建的:

    https://i.imgur.com/csXl8vl.png
    <br>
    CLC_DATE = the date of consumption, it's corresponding to each month in a year.
    <br>
    CLC_PRIX_PUBLIC = the turnover public
    <br>
    CLC_PRIX_CENTRALE = the turnover centrale

WHERE子句很重要,因为它是来自客户端的网关及其构成

使用您的解决方案,它不起作用。