練習 - 使用具體化函式最佳化查詢

已完成

在此練習中,您會使用 函 materialize 式來優化查詢。

回想一下,materialize 函式會在執行時快取子查詢的結果,以便查詢的其他部分可參考部分結果。

使用 materialize 函式

在我們的零售公司案例中,您的銷售小組會依營收和其貢獻百分比,要求您提供前 10 州的前幾大客戶。

若要提供這項資訊,您想要將查詢細分成階段,讓您可以在每個階段看到結果,如下所示:

  1. 執行下列查詢,依營收取得前幾大州。 let使用語句將子查詢指派給變數USCustomersUSCustomerSales

    執行查詢

    let USCustomers = Customers | where RegionCountryName == 'United States';
    let USCustomerSales =
        SalesFact
        | summarize USTotalCustomerSales = sum(SalesAmount) by CustomerKey
        | join kind=inner USCustomers on CustomerKey;
    USCustomerSales
    | summarize USTotalStateSales = round(sum(USTotalCustomerSales)) by StateProvinceName
    

    查看結果產生的清單。 請注意,資料表包含 StateProvinceNameUSTotalStateSales 的資料行。 您想要在結果中顯示省名,因此您必須將 Customers 數據表聯結至結果。

    Screenshot of the `materialize` function, showing the first block of the query.

  2. 執行下列查詢,將州內前幾大客戶的省別和詳細資料新增至結果。 您可以將子查詢聯 USCustomerSales 結至上一個查詢的結果,以新增此數據。

    現在,使用 materialize USCustomerSales數據表let語句中的函式來優化查詢。 這麼做只會執行指派的子查詢一次並快取結果。

    執行查詢

    let USCustomers = Customers | where RegionCountryName == 'United States';
    let USCustomerSales = materialize(
        SalesFact
        | summarize USTotalCustomerSales = sum(SalesAmount) by CustomerKey
        | join kind=inner USCustomers on CustomerKey);
    USCustomerSales
    | summarize USTotalStateSales = round(sum(USTotalCustomerSales)) by StateProvinceName
    | lookup (
        USCustomerSales
        | summarize arg_max(USTotalCustomerSales, *) by StateProvinceName
        )
        on StateProvinceName
    | top 10 by USTotalStateSales
    

    結果應該如下圖所示:

    Screenshot of the materialize function, showing the second block of the query.

  3. 執行下列查詢來輸出報告的資料行,並計算前幾大客戶對其州銷售量的貢獻 (以百分比表示)。

    執行查詢

    let Pcent = (portion: real, total: real) { round(100 * portion / total, 2) };
    let USCustomers = Customers | where RegionCountryName == 'United States';
    let USCustomerSales = materialize(
        SalesFact
        | summarize USTotalCustomerSales = sum(SalesAmount) by CustomerKey
        | join kind=inner USCustomers on CustomerKey);
    USCustomerSales
    | summarize USTotalStateSales = round(sum(USTotalCustomerSales)) by StateProvinceName
    | lookup (
        USCustomerSales
        | summarize arg_max(USTotalCustomerSales, *) by StateProvinceName
        )
        on StateProvinceName
    | top 10 by USTotalStateSales
    | project
        StateProvinceName,
        StateSales = USTotalStateSales,
        TopCustomerFirstName = FirstName,
        TopCustomerLastName = LastName,
        TopCustomerSales = round(USTotalCustomerSales),
        TopCustomerPercentage = Pcent(USTotalCustomerSales, USTotalStateSales)
    

    結果應該如下圖所示:

    Screenshot of the materialize function, showing the entire query.