如何将指定SQL语句转换为Power BI适用的DAX表达式?
Convert SQL Query to DAX for Power BI
Got it, let's map your SQL logic to a DAX expression that works seamlessly in Power BI. First, let's recap what your original query is accomplishing:
- It identifies the most recent transaction date (
Tx_Date) for eachSubtaskIDin theSupplierQuality_ASLtable - It joins back to the original table to get all columns for those latest records
- It filters those records to only keep ones where the transaction date is before March 28, 2018
- Finally, it sorts results by
SubtaskID(note: in Power BI, sorting is usually handled directly in report visuals rather than the DAX itself, but we’ll cover how to apply it post-creation)
Option 1: Using a Variable (Matches SQL Subquery Structure)
This approach mirrors your original SQL's subquery pattern, making it easy to follow and debug:
FilteredASLArchive = VAR LatestTxPerSubtask = // Replicates the SQL subquery: get max Tx_Date per SubtaskID SUMMARIZE( 'SupplierQuality_ASL', 'SupplierQuality_ASL'[SubtaskID], "MostRecentTx", MAX('SupplierQuality_ASL'[Tx_Date]) ) RETURN CALCULATETABLE( 'SupplierQuality_ASL', // Treat the variable table as a filter to "join" back to the original table TREATAS( LatestTxPerSubtask, 'SupplierQuality_ASL'[SubtaskID], 'SupplierQuality_ASL'[Tx_Date] ), // Filter for dates before 2018-03-28 'SupplierQuality_ASL'[Tx_Date] < DATE(2018, 3, 28), // Optional: Clear any existing context filters to match SQL's unfiltered result set ALL('SupplierQuality_ASL') )
Option 2: Concise DAX (Using Context Transition)
If you prefer a more compact version without variables, this uses ALLEXCEPT to calculate the max date per SubtaskID directly in the filter:
FilteredASLArchive = CALCULATETABLE( 'SupplierQuality_ASL', // Keep only records where Tx_Date is the latest for its SubtaskID 'SupplierQuality_ASL'[Tx_Date] = CALCULATE( MAX('SupplierQuality_ASL'[Tx_Date]), ALLEXCEPT('SupplierQuality_ASL', 'SupplierQuality_ASL'[SubtaskID]) ), // Apply the date filter 'SupplierQuality_ASL'[Tx_Date] < DATE(2018, 3, 28) )
Implementation Tips:
- Create the Calculated Table: Go to the Modeling tab in Power BI, select New Table, and paste either DAX expression. This will generate your desired dataset as a new table in the data model.
- Sorting: DAX calculated tables don’t retain an explicit sort order. To sort by
SubtaskID, select theSubtaskIDcolumn in the Fields pane, navigate to Column tools, and set the sort order to ascending. - Date Reliability: Using
DATE(2018, 3, 28)avoids regional date format issues that can come from string conversion, making your DAX more consistent across environments.
内容的提问来源于stack exchange,提问作者Calvin Ellington
相关产品推荐
相关产品推荐

