Dataset Preview
Duplicate
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code:   DatasetGenerationError
Exception:    CastError
Message:      Couldn't cast
text: string
prompt: string
response: string
to
{'prompt': Value('string'), 'response': Value('string')}
because column names don't match
Traceback:    Traceback (most recent call last):
                File "/usr/local/lib/python3.12/site-packages/datasets/builder.py", line 1779, in _prepare_split_single
                  for key, table in generator:
                                    ^^^^^^^^^
                File "/usr/local/lib/python3.12/site-packages/datasets/packaged_modules/json/json.py", line 299, in _generate_tables
                  self._cast_table(pa_table, json_field_paths=json_field_paths),
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.12/site-packages/datasets/packaged_modules/json/json.py", line 128, in _cast_table
                  pa_table = table_cast(pa_table, self.info.features.arrow_schema)
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.12/site-packages/datasets/table.py", line 2321, in table_cast
                  return cast_table_to_schema(table, schema)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.12/site-packages/datasets/table.py", line 2249, in cast_table_to_schema
                  raise CastError(
              datasets.table.CastError: Couldn't cast
              text: string
              prompt: string
              response: string
              to
              {'prompt': Value('string'), 'response': Value('string')}
              because column names don't match
              
              The above exception was the direct cause of the following exception:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1347, in compute_config_parquet_and_info_response
                  parquet_operations = convert_to_parquet(builder)
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 980, in convert_to_parquet
                  builder.download_and_prepare(
                File "/usr/local/lib/python3.12/site-packages/datasets/builder.py", line 882, in download_and_prepare
                  self._download_and_prepare(
                File "/usr/local/lib/python3.12/site-packages/datasets/builder.py", line 943, in _download_and_prepare
                  self._prepare_split(split_generator, **prepare_split_kwargs)
                File "/usr/local/lib/python3.12/site-packages/datasets/builder.py", line 1646, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
                File "/usr/local/lib/python3.12/site-packages/datasets/builder.py", line 1832, in _prepare_split_single
                  raise DatasetGenerationError("An error occurred while generating the dataset") from e
              datasets.exceptions.DatasetGenerationError: An error occurred while generating the dataset

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

prompt
string
response
string
Write a Fabric Warehouse T-SQL query to You can reference the table from added databases using three-part naming. In the following example, use the three-part name to refer toContosoSalesTablein the added databaseContosoLakehouse.
SELECT * FROM ContosoLakehouse.dbo.ContosoSalesTable AS Contoso INNER JOIN Affiliation ON Affiliation.AffiliationId = Contoso.RecordTypeID;
Write a Fabric Warehouse T-SQL query to Using three-part naming to reference the databases/tables, you can join multiple databases.
SELECT * FROM ContosoLakehouse.dbo.ContosoSalesTable AS Contoso INNER JOIN My_lakehouse.dbo.Affiliation ON My_lakehouse.dbo.Affiliation.AffiliationId = Contoso.RecordTypeID;
Write a Fabric Warehouse T-SQL query to For more efficient and longer queries, you can use aliases.
SELECT * FROM ContosoLakehouse.dbo.ContosoSalesTable AS Contoso INNER JOIN My_lakehouse.dbo.Affiliation as MyAffiliation ON MyAffiliation.AffiliationId = Contoso.RecordTypeID;
Write a Fabric Warehouse T-SQL query to Using three-part naming to reference the database and tables, you can insert data from one database to another.
INSERT INTO ContosoWarehouse.dbo.Affiliation SELECT * FROM My_Lakehouse.dbo.Affiliation;
Write a Fabric Warehouse T-SQL query to Update the table name and column definitions in theCREATE TABLEtemplate to match the structure you need. Your T-SQL script should look similar to the following code:.
CREATE TABLE [dbo].[bing_covid] ( id int, updated date, confirmed int, confirmed_change int, deaths int, deaths_change int, recovered int, recovered_change int, latitude float, longitude float, iso2 ...
Write a Fabric Warehouse T-SQL query to Create a loaded table in the SQL query editor from an external file You can also create a table directly from an external parquet file that you have access to. In this example, we'll create a new table based on a publicly available data file. In the query editor, paste and run th...
CREATE TABLE dbo.bing_covid AS SELECT * FROM OPENROWSET(BULK 'https://pandemicdatalake.blob.core.windows.net/public/curated/covid-19/bing_covid-19_data/latest/bing_covid-19_data.parquet');
Write a Fabric Warehouse T-SQL query to Examples of manual statistics maintenance To create statistics on thedbo.DimCustomertable, based on all the rows in a columnCustomerKey:.
CREATE STATISTICS DimCustomer_CustomerKey_FullScan ON dbo.DimCustomer (CustomerKey) WITH FULLSCAN;
Write a Fabric Warehouse T-SQL query to Examples of manual statistics maintenance To create statistics on thedbo.DimCustomertable, based on all the rows in a columnCustomerKey: To manually update the statistics objectDimCustomer_CustomerKey_FullScan, perhaps after a large data update:.
UPDATE STATISTICS dbo.DimCustomer (DimCustomer_CustomerKey_FullScan) WITH FULLSCAN;
Write a Fabric Warehouse T-SQL query to Examples of manual statistics maintenance To create statistics on thedbo.DimCustomertable, based on all the rows in a columnCustomerKey: To manually update the statistics objectDimCustomer_CustomerKey_FullScan, perhaps after a large data update: To show information about the stat...
DBCC SHOW_STATISTICS ("dbo.DimCustomer", "DimCustomer_CustomerKey_FullScan");
Write a Fabric Warehouse T-SQL query to Examples of manual statistics maintenance To create statistics on thedbo.DimCustomertable, based on all the rows in a columnCustomerKey: To manually update the statistics objectDimCustomer_CustomerKey_FullScan, perhaps after a large data update: To show information about the stat...
DBCC SHOW_STATISTICS ("dbo.DimCustomer", "DimCustomer_CustomerKey_FullScan") WITH HISTOGRAM;
Write a Fabric Warehouse T-SQL query to Examples of manual statistics maintenance To create statistics on thedbo.DimCustomertable, based on all the rows in a columnCustomerKey: To manually update the statistics objectDimCustomer_CustomerKey_FullScan, perhaps after a large data update: To show information about the stat...
DROP STATISTICS dbo.DimCustomer.DimCustomer_CustomerKey_FullScan;
Write a Fabric Warehouse T-SQL query to There are various cases where you can expect some type of automatic statistics. The most common are histogram-based statistics, which are requested by the query optimizer for columns referenced in GROUP BYs, JOINs, DISTINCT clauses, filters (WHERE clauses), and ORDER BYs. For exa...
SELECT <COLUMN_NAME> FROM <YOUR_TABLE_NAME> GROUP BY <COLUMN_NAME>;
Write a Fabric Warehouse T-SQL query to There are various cases where you can expect some type of automatic statistics. The most common are histogram-based statistics, which are requested by the query optimizer for columns referenced in GROUP BYs, JOINs, DISTINCT clauses, filters (WHERE clauses), and ORDER BYs. For exa...
select object_name(s.object_id) AS [object_name], c.name AS [column_name], s.name AS [stats_name], s.stats_id, STATS_DATE(s.object_id, s.stats_id) AS [stats_update_date], s.auto_created, s.user_created, s.stats_generation_method_desc FROM sys.stats AS s INNER JOIN sys.objects AS o ON...
Write a Fabric Warehouse T-SQL query to In this case, you should expect that statistics forCOLUMN_NAMEto have been created. If the column was also a varchar column, you would also see average column length statistics created. If you'd like to validate statistics were automatically created, you can run the following que...
DBCC SHOW_STATISTICS ('<YOUR_TABLE_NAME>', '<statistics_name>');
Write a Fabric Warehouse T-SQL query to In this case, you should expect that statistics forCOLUMN_NAMEto have been created. If the column was also a varchar column, you would also see average column length statistics created. If you'd like to validate statistics were automatically created, you can run the following que...
DBCC SHOW_STATISTICS ('sales.FactInvoice', '_WA_Sys_00000007_3B75D760');
Write a Fabric Warehouse T-SQL query to For example, you could commit inserts to multiples tables, or, none of the tables if an error arises. If you're changing details about a purchase order that affects three tables, you can group those changes into a single transaction. That means when those tables are queried, they...
-- Sample Syntax--- BEGIN TRAN; ALTER TABLE <table_name> ADD <column_name> <type>; ALTER TABLE <table_name> DROP COLUMN <column_name>; COMMIT;
Write a Fabric Warehouse T-SQL query to Cross-warehouse querying For more information on cross-warehouse querying, seeCross-warehouse querying. You can write a T-SQL query with the three-part naming convention to refer to objects and join them across warehouses, for example:.
SELECT emp.Employee ,SUM(Profit) AS TotalProfit ,SUM(Quantity) AS TotalQuantitySold FROM [SampleWarehouse].[dbo].[DimEmployee] as emp JOIN [WWI_Sample].[dbo].[FactSale] as sale ON emp.EmployeeKey = sale.SalespersonKey WHERE emp.IsSalesperson = 'TRUE' GROUP BY emp.Employee ORDER BY TotalProfit...
Write a Fabric Warehouse T-SQL query as shown in the Microsoft Fabric documentation.
%%sql SET spark.sql.parquet.vorder.default
Write Python/PySpark code for a Microsoft Fabric notebook as shown in the Microsoft Fabric documentation.
%%pyspark spark.conf.get('spark.sql.parquet.vorder.default')
Write Python/PySpark code for a Microsoft Fabric notebook as shown in the Microsoft Fabric documentation.
%%spark spark.conf.get('spark.sql.parquet.vorder.default')
Write Python/PySpark code for a Microsoft Fabric notebook as shown in the Microsoft Fabric documentation.
%%sparkr library(SparkR) sparkR.conf("spark.sql.parquet.vorder.default")
Write a Fabric Warehouse T-SQL query as shown in the Microsoft Fabric documentation.
%%sql SET spark.sql.parquet.vorder.default=FALSE
Write Python/PySpark code for a Microsoft Fabric notebook as shown in the Microsoft Fabric documentation.
%%pyspark spark.conf.set('spark.sql.parquet.vorder.default', 'false')
Write Python/PySpark code for a Microsoft Fabric notebook as shown in the Microsoft Fabric documentation.
%%spark spark.conf.set("spark.sql.parquet.vorder.default", "false")
Write Python/PySpark code for a Microsoft Fabric notebook as shown in the Microsoft Fabric documentation.
%%sparkr library(SparkR) sparkR.conf("spark.sql.parquet.vorder.default", "false")
Write a Fabric Warehouse T-SQL query as shown in the Microsoft Fabric documentation.
%%sql SET spark.sql.parquet.vorder.default=TRUE
Write Python/PySpark code for a Microsoft Fabric notebook as shown in the Microsoft Fabric documentation.
%%pyspark spark.conf.set('spark.sql.parquet.vorder.default', 'true')
Write Python/PySpark code for a Microsoft Fabric notebook as shown in the Microsoft Fabric documentation.
%%spark spark.conf.set("spark.sql.parquet.vorder.default", "true")
Write Python/PySpark code for a Microsoft Fabric notebook as shown in the Microsoft Fabric documentation.
%%sparkr library(SparkR) sparkR.conf("spark.sql.parquet.vorder.default", "true")
Write a Fabric Warehouse T-SQL query to Control V-Order using Delta table properties This section uses Spark SQL only because table properties are defined through SQL DDL andALTER TABLEstatements. Use table properties when you want a table-level default that applies across sessions. Enable V-Order table property during...
%%sql CREATE TABLE person (id INT, name STRING, age INT) USING parquet TBLPROPERTIES("delta.parquet.vorder.enabled" = "true");
Write a Fabric Warehouse T-SQL query to Use table properties when you want a table-level default that applies across sessions. Enable V-Order table property during table creation: When the table property is set totrue,INSERT,UPDATE, andMERGEapply V-Order at write time. Session-level and write-level settings still take ...
%%sql ALTER TABLE person SET TBLPROPERTIES("delta.parquet.vorder.enabled" = "true"); ALTER TABLE person SET TBLPROPERTIES("delta.parquet.vorder.enabled" = "false"); ALTER TABLE person UNSET TBLPROPERTIES("delta.parquet.vorder.enabled");
Write Python/PySpark code for a Microsoft Fabric notebook to This section uses PySpark to demonstrate the DataFrame writer API. The same pattern is available in Scala DataFrame APIs with equivalent options. Use write-level options when you need per-operation control instead of session-wide or table-wide defaults. All A...
df_source.write\ .format("delta")\ .mode("append")\ .saveAsTable("myschema.mytable") DeltaTable.createOrReplace(spark)\ .addColumn("id","INT")\ .addColumn("firstName","STRING")\ .addColumn("middleName","STRING")\ .addColumn("lastName","STRING",comment="surname")\ .addColumn("birthDate","TIMESTAMP")\ ...
Write Python/PySpark code for a Microsoft Fabric notebook to Use write-level options when you need per-operation control instead of session-wide or table-wide defaults. All Apache Spark write commands inherit the session setting when not explicitly overridden. The following examples write using V-Order by inheriting th...
df_source.write\ .format("delta")\ .mode("overwrite")\ .option("replaceWhere","start_date >= '2025-01-01' AND end_date <= '2025-01-31'")\ .option("parquet.vorder.enabled","true")\ .saveAsTable("myschema.mytable") DeltaTable.createOrReplace(spark)\ .addColumn("id","INT")\ .addColumn("firstName","STRING")\...
Write Python/PySpark code for a Microsoft Fabric notebook to Run the following commands in a notebook code cell. The first command installs thealtairlibrary. Also, installvega_datasets, which contains a semantic model you can use to visualize.
%conda install altair # install latest version through conda command %conda install vega_datasets # install latest version through conda command
Write Python/PySpark code for a Microsoft Fabric notebook to Import the package and semantic model by running the following code in another notebook cell.
import altair as alt from vega_datasets import data
Write Python/PySpark code for a Microsoft Fabric notebook to Now you can play around with the session-scopedaltairlibrary.
# load a simple dataset as a pandas DataFrame cars = data.cars() alt.Chart(cars).mark_point().encode( x='Horsepower', y='Miles_per_Gallon', color='Origin', ).interactive()
Write Python/PySpark code for a Microsoft Fabric notebook to Manage Python custom libraries through inline installation You can upload your Python custom libraries to the resources folder of your notebook or the attached environment. The resources folder is a built-in file system provided by each notebook and environme...
# install the .whl through pip command from the notebook built-in folder %pip install "builtin/wheel_file_name.whl"
Write Python/PySpark code for a Microsoft Fabric notebook to Now you can play around with the session-scopedcaesarlibrary with a Spark job.
library(SparkR) sparkR.session() hello <- function(x) { library(caesar) caesar(x) } spark.lapply(c("hello world", "good morning", "good evening"), hello)
Write Python/PySpark code for a Microsoft Fabric notebook to Manage Jar libraries through inline installation You can add.jarfiles to notebook sessions with the following command.
%%configure -f { "conf": { "spark.jars": "abfss://<<Lakehouse prefix>>.dfs.fabric.microsoft.com/<<path to JAR file>>/<<JAR file name>>.jar", } }
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Select a subset of columns Use theprojectoperator to simplify the view and select a specific subset of columns. Usingprojectis often more efficient and easier to read than viewing all columns.
StormEvents | take 5 | project State, EventType, DamageProperty
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Sort results To view the top floods in Texas that caused the most damage, use thesortoperator to arrange the rows in descending order based on theDamagePropertycolumn. The default sort order is descending. To sort in ascending order, specifyasc.
StormEvents | where State == 'TEXAS' and EventType == 'Flood' | sort by DamageProperty | project StartTime, EndTime, State, EventType, DamageProperty
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Filter by condition Thewhereoperator filters rows of data based on certain criteria. The following query looks for storm events in a specificStateof a specificEventType.
StormEvents | where State == 'TEXAS' and EventType == 'Flood' | project StartTime, EndTime, State, EventType, DamageProperty
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Filter by date and time range Use thebetween operatorto filter data based on a specific time range. The following query finds all storm events between August 1, 2007, and August 30, 2007, along with their states, event types, start times, and end times. T...
StormEvents | where StartTime between (datetime(2007-08-01 00:00:00) .. datetime(2007-08-30 23:59:59)) | project State, EventType, StartTime, EndTime | sort by StartTime asc
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Get the topnrows Thetopoperator returns the firstnrows sorted by the specified column. The following query returns the five Texas floods that caused the most damaged property.
StormEvents | where State == 'TEXAS' and EventType == 'Flood' | top 5 by DamageProperty | project StartTime, EndTime, State, EventType, DamageProperty
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Create calculated columns You can use theprojectandextendoperators to create calculated columns. Useprojectto specify only the columns you want to view. Useextendto add the calculated column to the end of the table. The following query creates a calculate...
StormEvents | where State == 'TEXAS' and EventType == 'Flood' | top 5 by DamageProperty desc | project StartTime, EndTime, Duration = EndTime - StartTime, DamageProperty
Write a KQL query for Microsoft Fabric Real-Time Intelligence to The following query creates a calculatedDurationcolumn with the difference between theStartTimeandEndTime. Since you only want to view a few select columns, usingprojectis the better choice in this case. If you take a look at the computedDurationcolumn, y...
StormEvents | where State == 'TEXAS' and EventType == 'Flood' | top 5 by DamageProperty desc | extend Duration = EndTime - StartTime
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Map values from one set to another Static mapping is a useful technique for changing the presentation of your results. In KQL, you can perform static mapping by using a dynamic dictionary and accessors to map values from one set to another.
let sourceMapping = dynamic( { "Emergency Manager" : "Public", "Utility Company" : "Private" }); StormEvents | where Source == "Emergency Manager" or Source == "Utility Company" | project EventId, Source, FriendlyName = sourceMapping[Source]
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Use the summarize operator Thesummarizeoperator is essential to performing aggregations over your data. Thesummarizeoperator groups together rows based on thebyclause and then uses the provided aggregation function to combine each group in a single row. F...
StormEvents | summarize TotalStorms = count() by State
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Visualize query results Visualizing query results in a chart or graph can help you identify patterns, trends, and outliers in your data. You can do this with therenderoperator. Throughout the tutorial, you'll see examples of how to userenderto display you...
StormEvents | summarize TotalStorms = count() by State | render barchart
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Conditionally count rows When analyzing your data, usecountif()to count rows based on a specific condition to understand how many rows meet the given criteria. The following query usescountif()to count of storms that caused damage. The query then uses the...
StormEvents | summarize StormsWithCropDamage = countif(DamageCrops > 0) by State | top 5 by StormsWithCropDamage
Write a KQL query for Microsoft Fabric Real-Time Intelligence to To aggregate by numeric or time values, you'll first want to group the data into bins using thebin()function. Usingbin()can help you understand how values are distributed within a certain range and make comparisons between different periods. The following...
StormEvents | where StartTime between (datetime(2007-01-01) .. datetime(2007-12-31)) and DamageCrops > 0 | summarize EventCount = count() by bin(StartTime, 7d)
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Calculate the min, max, avg, and sum To learn more about types of storms that cause crop damage, calculate themin(),max(), andavg()crop damage for each event type, and then sort the result by the average damage. Note that you can use multiple aggregation ...
StormEvents | where DamageCrops > 0 | summarize MaxCropDamage=max(DamageCrops), MinCropDamage=min(DamageCrops), AvgCropDamage=avg(DamageCrops) by EventType | sort by AvgCropDamage
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Note that you can use multiple aggregation functions in a singlesummarizeoperator to produce several computed columns. The results of the previous query indicate that Frost/Freeze events resulted in the most crop damage on average. However, thebin() query...
StormEvents | where StartTime between (datetime(2007-01-01) .. datetime(2007-12-31)) and DamageCrops > 0 | summarize CropDamage = sum(DamageCrops) by bin(StartTime, 7d) | render timechart
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Usecount()andcountifto find the percentage of storm events that caused crop damage in each state. First, count the total number of storms in each state. Then, count the number of storms that caused crop damage in each state. Then, useextendto calculate th...
StormEvents | summarize TotalStormsInState = count(), StormsWithCropDamage = countif(DamageCrops > 0) by State | extend PercentWithCropDamage = round((todouble(StormsWithCropDamage) / TotalStormsInState * 100), 2) | sort by StormsWithCropDamage
Write a KQL query for Microsoft Fabric Real-Time Intelligence to To compare the number of storms by event type to the total number of storms in the database, first save the total number of storms in the database as a variable.Let statementsare used to define variables within a query. Sincetabular expression statementsr...
let TotalStorms = toscalar(StormEvents | summarize count()); StormEvents | summarize EventCount = count() by EventType | project EventType, EventCount, Percentage = todouble(EventCount) / TotalStorms * 100.0
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Extract unique values Usemake_set()to turn a selection of rows in a table into an array of unique values. The following query usesmake_set()to create an array of the event types that cause deaths in each state. The resulting table is then sorted by the nu...
StormEvents | where DeathsDirect > 0 or DeathsIndirect > 0 | summarize StormTypesWithDeaths = make_set(EventType) by State | project State, StormTypesWithDeaths | sort by array_length(StormTypesWithDeaths)
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Bucket data by condition Thecase()function groups data into buckets based on specified conditions. The function returns the corresponding result expression for the first satisfied predicate, or the final else expression if none of the predicates are satis...
StormEvents | summarize InjuriesCount = sum(InjuriesDirect) by State | extend InjuriesBucket = case ( InjuriesCount > 50, "Large", InjuriesCount > 10, "Medium", InjuriesC...
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Thecase()function groups data into buckets based on specified conditions. The function returns the corresponding result expression for the first satisfied predicate, or the final else expression if none of the predicates are satisfied. This example groups...
StormEvents | summarize InjuriesCount = sum(InjuriesDirect) by State | extend InjuriesBucket = case ( InjuriesCount > 50, "Large", InjuriesCount > 10, "Medium", InjuriesC...
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Perform aggregations over a sliding window The following example shows how to summarize columns using a sliding window. The query calculates the minimum, maximum, and average property damage of tornados, floods, and wildfires using a sliding window of sev...
let windowStart = datetime(2007-07-01); let windowEnd = windowStart + 13d; StormEvents | where EventType in ("Tornado", "Flood", "Wildfire") | extend bin = bin_at(startofday(StartTime), 1d, windowStart) // 1 | extend endRange = iff(bin + 7d > windowEnd, windowEnd, iff(bin + 7d - 1d < windowStart...
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Examples The following example determines what unique combinations ofStateandEventTypethere are for storms that resulted in direct injury. There are no aggregation functions, just group-by keys. The output displays only the columns for those results.
StormEvents | where InjuriesDirect > 0 | summarize by State, EventType
Write a KQL query for Microsoft Fabric Real-Time Intelligence to The following example determines what unique combinations ofStateandEventTypethere are for storms that resulted in direct injury. There are no aggregation functions, just group-by keys. The output displays only the columns for those results. The following...
StormEvents | where State == "HAWAII" and EventType == "Heavy Rain" | project Duration = EndTime - StartTime | summarize Min = min(Duration), Max = max(Duration)
Write a KQL query for Microsoft Fabric Real-Time Intelligence to The following example calculates the number of unique storm event types for each state and sorts the results by the number of unique storm types:.
StormEvents | summarize TypesOfStorms=dcount(EventType) by State | sort by TypesOfStorms
Write a KQL query for Microsoft Fabric Real-Time Intelligence to The following example calculates the number of unique storm event types for each state and sorts the results by the number of unique storm types: The following table shows only the first 5 rows. To see the full output, run the query. The following example...
StormEvents | project EventType, Duration = EndTime - StartTime | where Duration > 1d | summarize EventCount=count() by EventType, Length=bin(Duration, 1d) | sort by Length
Write a KQL query for Microsoft Fabric Real-Time Intelligence to The following example shows the default values of aggregates when the input table is empty. Thesummarizeoperator is used to calculate the default values of the aggregates. When the input ofsummarizeoperator has at least one empty group-by key, its result ...
datatable(x:long)[] | summarize any_x=take_any(x), arg_max_x=arg_max(x, *), arg_min_x=arg_min(x, *), avg(x), buildschema(todynamic(tostring(x))), max(x), min(x), percentile(x, 55), hll(x) ,stdev(x), sum(x), sumif(x, x > 0), tdigest(x), variance(x)
Write a KQL query for Microsoft Fabric Real-Time Intelligence to The following example shows the default values of aggregates when the input table is empty. Thesummarizeoperator is used to calculate the default values of the aggregates. When the input ofsummarizeoperator has at least one empty group-by key, its result ...
datatable(x:long)[] | summarize count(x), countif(x > 0) , dcount(x), dcountif(x, x > 0)
Write a KQL query for Microsoft Fabric Real-Time Intelligence to The result ofavg_x(x)isNaNdue to dividing by 0.
datatable(x:long)[] | summarize make_set(x), make_list(x)
Write a KQL query for Microsoft Fabric Real-Time Intelligence to The avg aggregate sums only the non-null values and counts only those values in its calculation, ignoring any nulls.
range x from 1 to 4 step 1 | extend y = iff(x == 1, real(null), real(5)) | summarize sum(y), avg(y)
Write a KQL query for Microsoft Fabric Real-Time Intelligence to The avg aggregate sums only the non-null values and counts only those values in its calculation, ignoring any nulls. The standard count function includes null values in its count:.
range x from 1 to 2 step 1 | extend y = iff(x == 1, real(null), real(5)) | summarize count(y)
Write a KQL query for Microsoft Fabric Real-Time Intelligence to The standard count function includes null values in its count:.
range x from 1 to 2 step 1 | extend y = iff(x == 1, real(null), real(5)) | summarize make_set(y), make_set(y)
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Order comparisons by complexity The following query returns storm records that report damaged property, are floods, and start and end in different places. Notice that we put the comparison between two columns last, as the where operator can't use the inde...
StormEvents | project DamageProperty, EventType, BeginLocation, EndLocation | where DamageProperty > 0 and EventType == "Flood" and BeginLocation != EndLocation
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Define scalar values The following example uses a scalar expression statement.
let threshold = 50; let region = "West"; datatable(Name:string, Score:int, Region:string) [ "Alice", 45, "West", "Bob", 60, "East", "Charlie", 55, "West", "Dana", 70, "North" ] | where Score > threshold and Region == region
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Define tabular expressions The following example binds the namesome numberusing the['name']notation, and then uses it in a tabular expression statement.
let ['some number'] = 20; range y from 0 to ['some number'] step 5
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Create a user defined function with scalar calculation This example uses the let statement with arguments for scalar calculation. The query defines functionMultiplyByNfor multiplying two numbers.
let MultiplyByN = (val:long, n:long) { val * n }; range x from 1 to 5 step 1 | extend result = MultiplyByN(x, 5)
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Create a user defined function that trims input The following example removes leading and trailing ones from the input.
let TrimOnes = (s:string) { trim("1", s) }; range x from 10 to 15 step 1 | extend result = TrimOnes(tostring(x))
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Use multiple let statements This example defines two let statements where one statement (foo2) uses another (foo1).
let foo1 = (_start:long, _end:long, _step:long) { range x from _start to _end step _step}; let foo2 = (_step:long) { foo1(1, 100, _step)}; foo2(2) | count
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Create a view or virtual table This example shows you how to use a let statement to create aviewor virtual table.
let Range10 = view () { range MyColumn from 1 to 10 step 1 }; let Range20 = view () { range MyColumn from 1 to 20 step 1 }; search MyColumn == 5
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Use a materialize function Thematerialize()function lets you cache subquery results during the time of query execution. When you use thematerialize()function, the data is cached, and any subsequent invocation of the result uses cached data.
let TotalEventsbyLocation = StormEvents | summarize TotalCount = count() by Location = BeginLocation; let materializedScope = StormEvents | summarize by EventType, Location = EndLocation; let cachedResult = materialize(materializedScope); cachedResult | project EventType, Location | join kind = inner ( cachedResult...
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Using nested let statements Nested let statements are permitted, including within a user defined function expression. Let statements and arguments apply in both the current and inner scope of the function body.
let start_time = ago(5h); let end_time = start_time + 2h; T | where Time > start_time and Time < end_time | ...
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Tabular argument with schema The following example specifies that the table parameterTmust have a columnStateof typestring. The tableTmay include other columns as well, but they can't be referenced in the functionStateStatebecause the aren't declared.
let StateState=(T: (State: string)) { T | extend s_s=strcat(State, State) }; StormEvents | invoke StateState() | project State, s_s
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Tabular argument with wildcard The table parameterTcan have any schema, and the functionCountRecordsInTablewill work.
let CountRecordsInTable=(T: (*)) { T | count }; StormEvents | invoke CountRecordsInTable()
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Regex mode In regex mode, parse translates the pattern to a regex. Useregular expressionsto do the matching and use numbered captured groups that are handled internally. For example:.
parse kind=regex Col with * <regex1> var1:string <regex2> var2:long
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Parse and extend results In the following example, the columnEventTextof tableTracescontains strings of the formEvent: NotifySliceRelease (resourceName={0}, totalSlices={1}, sliceNumber={2}, lockTime={3}, releaseTime={4}, previousLockTime={5}). The operat...
let Traces = datatable(EventText: string) [ "Event: NotifySliceRelease (resourceName=PipelineScheduler, totalSlices=27, sliceNumber=23, lockTime=02/17/2016 08:40:01, releaseTime=02/17/2016 08:40:01, previousLockTime=02/17/2016 08:39:01)", "Event: NotifySliceRelease (resourceName=PipelineScheduler, totalSlic...
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Extract email alias and DNS In the following example, entries from theContactstable are parsed to extract the alias and domain from an email address, and the domain from a website URL. The query returns theEmailAddress,EmailAlias, andWebsiteDomaincolumns,...
let Leads=datatable(Contacts: string) [ "Event: LeadContact (email=john@contosohotel.com, Website=https:contosohotel.com)", "Event: LeadContact (email=abi@fourthcoffee.com, Website=https:www.fourthcoffee.com)", "Event: LeadContact (email=nevena@treyresearch.com, Website=https:treyresearch.com)", "Event: Lead...
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Regex mode In the following example, regular expressions are used to parse and extract data from theEventTextcolumn. The extracted data is projected into new fields.
let Traces=datatable(EventText: string) [ "Event: NotifySliceRelease (resourceName=PipelineScheduler, totalSlices=27, sliceNumber=23, lockTime=02/17/2016 08:40:01, releaseTime=02/17/2016 08:40:01, previousLockTime=02/17/2016 08:39:01)", "Event: NotifySliceRelease (resourceName=PipelineScheduler, totalSlices...
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Regex mode with regex flags In the following exampleresourceNameis extracted.
let Traces=datatable(EventText: string) [ "Event: NotifySliceRelease (resourceName=PipelineScheduler, totalSlices=27, sliceNumber=23, lockTime=02/17/2016 08:40:01, releaseTime=02/17/2016 08:40:01, previousLockTime=02/17/2016 08:39:01)", "Event: NotifySliceRelease (resourceName=PipelineScheduler, totalSlices...
Write a KQL query for Microsoft Fabric Real-Time Intelligence to In the following exampleresourceNameis extracted. If there are records whereresourceNamesometimes appears as lower-case and sometimes as upper-case, you might get nulls for some values. The results in the previous example are unexpected, and include full ...
let Traces=datatable(EventText: string) [ "Event: NotifySliceRelease (resourceName=PipelineScheduler, totalSlices=27, sliceNumber=23, lockTime=02/17/2016 08:40:01, releaseTime=02/17/2016 08:40:01, previousLockTime=02/17/2016 08:39:01)", "Event: NotifySliceRelease (resourceName=PipelineScheduler, totalSlices...
Write a KQL query for Microsoft Fabric Real-Time Intelligence to If there are records whereresourceNamesometimes appears as lower-case and sometimes as upper-case, you might get nulls for some values. The results in the previous example are unexpected, and include full event data since the default mode is greedy. To ex...
let Traces=datatable(EventText: string) [ "Event: NotifySliceRelease (resourceName=PipelineScheduler\ntotalSlices=27\nsliceNumber=23\nlockTime=02/17/2016 08:40:01\nreleaseTime=02/17/2016 08:40:01\npreviousLockTime=02/17/2016 08:39:01)", "Event: NotifySliceRelease (resourceName=PipelineScheduler\ntotalSlices...
Write a KQL query for Microsoft Fabric Real-Time Intelligence to In the following relaxed mode example, the extended columntotalSlicesmust be of typelong. However, in the parsed string, it has the valuenonValidLongValue. For the extended column,releaseTime, the valuenonValidDateTimecan't be parsed asdatetime. These two...
let Traces=datatable(EventText: string) [ "Event: NotifySliceRelease (resourceName=PipelineScheduler, totalSlices=27, sliceNumber=23, lockTime=02/17/2016 08:40:01, releaseTime=nonValidDateTime 08:40:01, previousLockTime=02/17/2016 08:39:01)", "Event: NotifySliceRelease (resourceName=PipelineScheduler, total...
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Examples The following example shows how to use theextendoperator to create a new column calledDurationthat calculates the difference between theEndTimeandStartTimecolumns in theStormEventstable.
StormEvents | project EndTime, StartTime | extend Duration = EndTime - StartTime
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Only show specific columns Only show theEventId,State,EventTypeof theStormEventstable.
StormEvents | project EventId, State, EventType
Write a KQL query for Microsoft Fabric Real-Time Intelligence to Potential manipulations using project The following query renames theBeginLocationcolumn and creates a new column calledTotalInjuriesfrom a calculation over two existing columns.
StormEvents | project StartLocation = BeginLocation, TotalInjuries = InjuriesDirect + InjuriesIndirect | where TotalInjuries > 5
Write a DAX expression for a Fabric semantic model to A calculated column is a column that you add to an existing table (in the model designer) and then create a DAX formula that defines the column's values. When a calculated column contains a valid DAX formula, values are calculated for each row as soon as the formula...
= [Calendar Year] & " Q" & [Calendar Quarter]
Write a DAX expression for a Fabric semantic model to DAX queries can be created and run in SQL Server Management Studio (SSMS) and open-source tools like DAX Studio (daxstudio.org). Unlike DAX calculation formulas, which can only be created in tabular data models, DAX queries can also be run against Analysis Services ...
EVALUATE ( FILTER ( 'DimProduct', [SafetyStockLevel] < 200 ) ) ORDER BY [EnglishProductName] ASC
Write a DAX expression for a Fabric semantic model to Formula basics DAX formulas can be very simple or quite complex. The following table shows some examples of simple formulas that could be used in a calculated column. Whether the formula you create is simple or complex, you can use the following steps when building ...
Days in Current Quarter = COUNTROWS( DATESBETWEEN( 'Date'[Date], STARTOFQUARTER( LASTDATE('Date'[Date])), ENDOFQUARTER('Date'[Date])))
Write a DAX expression for a Fabric semantic model to Variables You can create variables within an expression by usingVAR. VAR is technically not a function, it's a keyword to store the result of an expression as a named variable. That variable can then be passed as an argument to other measure expressions. For example...
VAR TotalQty = SUM ( Sales[Quantity] ) Return IF ( TotalQty > 1000, TotalQty * 0.95, TotalQty * 1.25 )
Write a DAX expression for a Fabric semantic model to Row context also follows any relationships that have been defined between tables, including relationships defined within a calculated column by using DAX formulas, to determine which rows in related tables are associated with the current row. For example, the follow...
= [Freight] + RELATED('Region'[TaxRate])
Write a DAX expression for a Fabric semantic model to For example, suppose your model contains aProductstable and aSalestable. Users might want to go through the entire sales table, which is full of transactions involving multiple products, and find the largest quantity ordered for each product in any one transaction. ...
= MAXX(FILTER(Sales,[ProdKey] = EARLIER([ProdKey])),Sales[OrderQty])
Write a DAX expression for a Fabric semantic model to Referring to tables and columns in formulas You can refer to any table and column by using its name. For example, the following formula illustrates how to refer to columns from two tables by using thefully qualifiedname:.
= SUM('New Sales'[Amount]) + SUM('Past Sales'[Amount])
Write a DAX expression for a Fabric semantic model to Syntax.
CALCULATE(<expression>[, <filter1> [, <filter2> [, …]]])
Write a DAX expression for a Fabric semantic model as shown in the Microsoft Fabric documentation.
Total sales on the last selected date = CALCULATE ( SUM ( Sales[Sales Amount] ), 'Sales'[OrderDateKey] = MAX ( 'Sales'[OrderDateKey] ) )
End of preview.

No dataset card yet

Downloads last month
6