SQL子查询以显示总计百分比

时间:2018-06-29 12:09:38

标签: sql

我正在尝试获取一个包含以下3列的表

  1. 地理区域(FSA)
  2. 销售(GRS_CAD)
  3. 总计百分比(总计百分比),即第2列中的值除以第2列中所有值的总和。

我有2个约束,因为我将在Tableau仪表板中使用查询:

  • 无法声明变量
  • 无法创建临时表

对此我还很陌生,我尝试了嵌套查询。我得到的结果几乎是“看起来”正确的,但是我相信我的第三列的分母会针对每一行而变化,而事实并非如此。另外,当我只运行分母的子查询时,我得到了正确的数字,因此我猜想它可能与查询的执行顺序有关。

你能帮忙吗?

SELECT  
SubTable.FSA 
, SubTable.GRS_CAD 
, SubTable.GRS_CAD/

        (
        SELECT sum(RPTOP.totaladjrevenue_onehr)

        FROM  csn_order.dbo.tblorderproduct OP (nolock)
        JOIN csn_report.dbo.rptorderproduct RPTOP (nolock) on OP.opid = RPTOP.opid
        JOIN csn_order.dbo.tblplstate PLSTATE (nolock) on OP.oprestid = PLSTATE.StID

        WHERE RPTOP.OrderSourceStoreID=446 
        AND RPTOP.Cancelled=0 
        AND RPTOP.OrCompleteDate > '2018-01-01' 
        AND PLSTATE.StID>=55 
        AND PLSTATE.StID<=67
        ) as 'Percent of total GRS'

FROM

    (SELECT 
         FSA = LEFT(A.oprepostalcode,3)
         , sum(B.totaladjrevenue_onehr) GRS_CAD
    FROM csn_order.dbo.tblorderproduct A (nolock)
        JOIN csn_report.dbo.rptorderproduct B (nolock) on A.opid = B.opid
        JOIN csn_order.dbo.tblplstate C (nolock) on A.oprestid = C.StID
    WHERE B.Ordersourcestoreid = 446
        AND B.cancelled = 0
        AND B.OrCompleteDate > '2018-01-01'
        AND C.StID >= 55 
        AND C.StID<=67
    GROUP BY LEFT(A.oprepostalcode,3))
 as SubTable

1 个答案:

答案 0 :(得分:0)

您始终可以使用此技术来转换像您一样的查询。这将始终创建efficient SQL statement,因为每个行都不会执行每个选择语句。

  1. 将您的select语句移至 from 子句。
  2. 为您的select语句和所需的列命名。

    SELECT SubTable.FSA,
           SubTable.GRS_CAD,
           SubTable.GRS_CAD / PercentTotalOFGRS.TempName
    FROM
    (
        SELECT FSA = LEFT(A.oprepostalcode, 3),
               SUM(B.totaladjrevenue_onehr) GRS_CAD
        FROM csn_order.dbo.tblorderproduct A (NOLOCK)
            JOIN csn_report.dbo.rptorderproduct B (NOLOCK)
                ON A.opid = B.opid
            JOIN csn_order.dbo.tblplstate C (NOLOCK)
                ON A.oprestid = C.StID
        WHERE B.Ordersourcestoreid = 446
              AND B.cancelled = 0
              AND B.OrCompleteDate > '2018-01-01'
              AND C.StID >= 55
              AND C.StID <= 67
        GROUP BY LEFT(A.oprepostalcode, 3)
    ) AS SubTable ,
    (
        SELECT SUM(RPTOP.totaladjrevenue_onehr) AS TempName
        FROM csn_order.dbo.tblorderproduct OP (NOLOCK)
            JOIN csn_report.dbo.rptorderproduct RPTOP (NOLOCK)
                ON OP.opid = RPTOP.opid
            JOIN csn_order.dbo.tblplstate PLSTATE (NOLOCK)
                ON OP.oprestid = PLSTATE.StID
        WHERE RPTOP.OrderSourceStoreID = 446
              AND RPTOP.Cancelled = 0
              AND RPTOP.OrCompleteDate > '2018-01-01'
              AND PLSTATE.StID >= 55
              AND PLSTATE.StID <= 67
    ) AS PercentTotalOFGRS;