求和子查询

时间:2014-11-13 18:02:12

标签: tsql sql-server-2008-r2

我正在尝试创建一个查询,该查询总结了来自此表中实体的52周数据的销售额。

enter image description here

我想出了如何使用以下查询获取CYSales的过去52周。年和周将最终成为结果报告中的参数,因此这些值是任意的。我只使用当前年份和第40周这个例子。

SELECT  [Group],[Owner],[SalesPersonNumber],SUM([tot_sls_amt]) AS CYSales
  FROM TableA
  WHERE ((Year = year(getdate()) AND Week <= 40) OR (Year = year(getdate()) - 1 AND Week > 40)) AND cmp_status = 'A'
  Group BY [Group] 
      ,[Owner]
      ,[SalesPersonNumber]

这给了我这个

enter image description here

我现在正试图在另一个计算列中获取PYSales数量,但是当我添加子查询时,我收到错误

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

如何修复以下查询以便为我提供PYSales?

SELECT  [Group]
        ,[Owner]
        ,[SalesPersonNumber]
        ,SUM([tot_sls_amt]) AS CYSales
        ,(SELECT SUM([tot_sls_amt]) 
          FROM TableA
          WHERE ((Year = year(getdate())-1 AND Week <= 40) OR (Year = year(getdate()) - 2 AND Week > 40)) AND cmp_status = 'A'
          Group BY [Group] ,[Owner],[SalesPersonNumber]) AS PYSales
  FROM TableA
  WHERE ((Year = year(getdate()) AND Week <= 40) OR (Year = year(getdate()) - 1 AND Week > 40)) AND cmp_status = 'A'
  Group BY [Group] 
          ,[Owner]
          ,[SalesPersonNumber]

2 个答案:

答案 0 :(得分:1)

我会移动您的子查询并加入它或使用cte。

我使用左连接,因为你有一个新的,没有py的数据

没有测试数据,如果出现故障我可以告诉我,我可以修改。

SELECT  

a.[Group]
,a.[Owner]
,a.[SalesPersonNumber]
,SUM(a.[tot_sls_amt]) AS CYSales
,(b.[tot_sls_amt]) AS PYSales

  FROM 

TableA a
        Left Join 
            (SELECT sum([tot_sls_amt]) tot_sls_amt,[Group],[Owner] ,[SalesPersonNumber]
                 FROM TableA
                     WHERE ((Year = year(getdate())-1 AND Week <= 40) OR (Year = year(getdate()) - 2 AND Week > 40)) AND cmp_status = 'A'
                        group by [Group],[Owner] ,[SalesPersonNumber]) b on a.group = b.group and a.owner = b.owner and a.salespersonumber =b.salespersonnumber



WHERE 
((Year = year(getdate()) AND Week <= 40) OR (Year = year(getdate()) - 1 AND Week > 40)) AND cmp_status = 'A'


Group BY 
a.[Group] 
,a.[Owner]
,a.[SalesPersonNumber]
,(b.[tot_sls_amt])

答案 1 :(得分:0)

您正在子查询中执行GROUP BY,它将返回每对Group,Owner,SalesPersonNumber的总和,这与您的外部查询相同。

如果你只需要给定周和年的所有值的总计,只需做总和并使用交叉申请

SELECT  [Group]
        ,[Owner]
        ,[SalesPersonNumber]
        ,SUM([tot_sls_amt]) AS CYSales,
        T.total AS PYSales
  FROM TableA
  WHERE ((Year = year(getdate()) AND Week <= 40) OR (Year = year(getdate()) - 1 AND Week > 40)) AND cmp_status = 'A'
  Group BY [Group] 
          ,[Owner]
          ,[SalesPersonNumber]
  CROSS APPLY (
          SELECT SUM([tot_sls_amt])  as total
          FROM TableA
          WHERE ((Year = year(getdate())-1 AND Week <= 40) OR (Year = year(getdate()) - 2 AND Week > 40)) AND cmp_status = 'A'
          ) As T