具有多个值错误的子查询。具有多列的案例

时间:2017-02-20 12:42:05

标签: sql sql-server

我正在尝试创建一个包含3列的查询:1列表示列表作业编号(非空值),2°和3列表示特定日期之前和之后的值之和

SQL Server出错了,我真的不知道如何解决它(除了创建2个查询..)

SELECT 
    (SELECT
         PiIndex
     FROM 
         EleGcImpianti
     WHERE 
         PiIndex IS NOT NULL) AS Commessa,
    (SELECT
         SUM(PrImportoDaFatturare)
     FROM 
         EleGcPianificazioneRate
     RIGHT OUTER JOIN 
         EleGcImpianti ON EleGcPianificazioneRate.PrIdImpianto = EleGcImpianti.PiId
     WHERE 
         (EleGcPianificazioneRate.PrDataFattura <= CONVERT(datetime, '2014-01-01', 102))) AS [Somma Rate],
    (SELECT
         SUM(PrPercentualeDaFatturare)
     FROM 
         EleGcPianificazioneRate
     RIGHT OUTER JOIN 
         EleGcImpianti ON EleGcPianificazioneRate.PrIdImpianto = EleGcImpianti.PiId
     WHERE 
         (PrDataFattura > CONVERT(datetime, '2014-01-01', 102))) AS [Somma Percentuale Rate]

2 个答案:

答案 0 :(得分:1)

您似乎只想从EleGcImpianti中选择记录,并希望获得EleGcPianificazioneRate的相关金额:

SELECT 
  i.PiIndex,
  COALESCE(pr.sum_after, 0) AS sum_after_date, 
  COALESCE(pr.sum_before, 0) AS sum_before_date
FROM EleGcImpianti i
LEFT JOIN
(
  SELECT
    PrIdImpianto,
    SUM(CASE WHEN PrDataFattura <= '20140101' THEN PrImportoDaFatturare END) AS sum_after,
    SUM(CASE WHEN PrDataFattura > '20140101' THEN PrImportoDaFatturare END) AS sum_before
  FROM EleGcPianificazioneRate
  GROUP BY PrIdImpianto
) pr ON pr.PrIdImpianto = i.PiId
WHERE i.PiIndex IS NOT NULL

答案 1 :(得分:0)

您的查询在语法上无效SQL:没有用于收集结果的表/视图(除了子查询内)。

以下(未经测试的)查询...

  • ...定义从截止日期条件
  • 派生的指标变量after_cutoff
  • ...从相应无关紧要的时间删除汇总的基本值
  • 执行全局总结
  • 忽略PiIndex列 - 使用此信息,而汇总数据只有在数据分区的一部分才有意义。

这应该产生一个带有求和结果的记录。

请注意,选择性求和值的常用SQL习惯用法是group by子句。但是,结果将包括各自“不感兴趣”的总结结果。日期时间间隔。

这导致建议您可能要检查是否确实要将两个汇总应用于补充日期时间 - 列名称表示您要汇总 all < / em>值具有所有日期(或至少相同的时间段)的绝对值和百分比。

    select sum(sq2.base_sum_rate)       AS [Somma Rate]
         , sum(sq2.base_sum_pct_rate)   AS [Somma Percentuale Rate]
      from (   
               select sq1.after_cutoff
                    , sq1.PrImportoDaFatturare     * (1 - sq1.after_cutoff)  base_sum_rate
                    , sq1.PrPercentualeDaFatturare * sq1.after_cutoff        base_sum_pct_rate
                 from (
                              select *
                                   , CASE WHEN EleGcPianificazioneRate.PrDataFattura <= CONVERT(DATETIME, '2014-01-01', 102) THEN 0 ELSE 1 END after_cutoff
                                from EleGcPianificazioneRate
                         RIGHT OUTER JOIN EleGcImpianti ON EleGcPianificazioneRate.PrIdImpianto = EleGcImpianti.PiId
                               where EleGcImpianti.PiIndex IS NOT NULL
                      ) sq1
           ) sq2
         ;