如何将SQL转换为DAX并在Power BI Desktop中创建计算表

时间:2018-02-01 19:20:27

标签: powerbi dax powerbi-embedded power-bi-report-server

我有一个包含3列的表格:EffectiveDateActualStatusPredictedStatus

enter image description here

我需要按EffectiveDate分组,并计算ActualStatus列和PredictedStatus列的每个状态的数量。

在sql中,我会这样做:

 select EffectiveDate,
        ActualStatus,
        SUM(case when ActualStatus = 'Bound' then 1 
                 when ActualStatus = 'Declined' then 1
                 when ActualStatus = 'Quoted' then 1
                 when ActualStatus = 'Not Taken Up' then 1
                 when ActualStatus = 'Indication' then 1
                 when ActualStatus = 'Submitted' then 1
                 when ActualStatus = 'Lost' then 1
                 when ActualStatus = 'Indicated' then 1
        else 0 end) as CountActual,
        PredictedStatus,
        SUM(case when PredictedStatus = 'Bound' then 1
                 when PredictedStatus = 'Not Bound' then 1
                 ELSE NULL end) as CountPredicted

from #Test
group by 
        EffectiveDate,
        ActualStatus,
        PredictedStatus

结果应如下所示:

enter image description here

1 个答案:

答案 0 :(得分:1)

要遵循相同的逻辑,请创建两个类似于SQL case语句的计算列。

if [ActualStatus] = "Bound" or
   [ActualStatus] = "Declined" or
   [ActualStatus] = "Quoted" or
   [ActualStatus] = "Not Taken Up" or
   [ActualStatus] = "Indication" or
   [ActualStatus] = "Submitted" or
   [ActualStatus] = "Lost" or
   [ActualStatus] = "Indicated"
then 1
else 0

if [PredictedStatus] = "Bound" or
   [PredictedStatus] = "Not Bound"
then 1
else null

然后按前三列分组并汇总其他列,如下所示:

GroupBy

生成的查询在高级编辑器中看起来像这样:

let
    Test = <Insert Data Source Here>,
    #"Added Custom" = Table.AddColumn(Test, "CountActual", each if [ActualStatus] = "Bound" or [ActualStatus] = "Declined" or [ActualStatus] = "Quoted" or [ActualStatus] = "Not Taken Up" or [ActualStatus] = "Indication" or [ActualStatus] = "Submitted" or [ActualStatus] = "Lost" or [ActualStatus] = "Indicated" then 1 else 0),
    #"Added Custom1" = Table.AddColumn(#"Added Custom", "CountPredicted", each if [PredictedStatus] = "Bound" or [PredictedStatus] = "Not Bound" then 1 else null),
    #"Grouped Rows" = Table.Group(#"Added Custom1", {"Day", "ActualStatus", "PredictedStatus"}, {{"CountActual", each List.Sum([CountActual]), type number}, {"CountPredicted", each List.Sum([CountPredicted]), type number}}),
    #"Reordered Columns" = Table.ReorderColumns(#"Grouped Rows",{"Day", "ActualStatus", "CountActual", "PredictedStatus", "CountPredicted"})
in
    #"Reordered Columns"