Te treści nie są jeszcze zoptymalizowane pod kątem urządzeń mobilnych.
Dla maksymalnej wygody odwiedź nas na komputerze, korzystając z linku przesłanego e-mailem.
Overview
BigQuery is Google's fully managed, NoOps, low cost analytics database. With BigQuery you can query terabytes and terabytes of data without having any infrastructure to manage or needing a database administrator. BigQuery uses SQL and can take advantage of the pay-as-you-go model. BigQuery allows you to focus on analyzing data to find meaningful insights.
The dataset you'll use is an ecommerce dataset that has millions of Google Analytics records for the Google Merchandise Store loaded into BigQuery. You have a copy of that dataset for this lab and will explore the available fields and row for insights.
This lab you will learn how to create new permanent reporting tables and logical reviews from an existing ecommerce dataset.
Setup and requirements
For each lab, you get a new Google Cloud project and set of resources for a fixed time at no cost.
Sign in to Google Skills using an incognito window.
Note the lab's access time (for example, 1:15:00), and make sure you can finish within that time.
There is no pause feature. You can restart if needed, but you have to start at the beginning.
When ready, click Start lab.
Note your lab credentials (Username and Password). You will use them to sign in to the Google Cloud Console.
Click Open Google Console.
Click Use another account and copy/paste credentials for this lab into the prompts.
If you use other credentials, you'll receive errors or incur charges.
Accept the terms and skip the recovery resource page.
Open BigQuery Console
In the Google Cloud Console, select Navigation menu > BigQuery.
The Welcome to BigQuery in the Cloud Console message box opens. This message box provides a link to the quickstart guide and lists UI updates.
Click Done.
Task 1. Create a new dataset to store the tables
In BigQuery, click on view actions near your project name, then click Create Dataset.
In the Dataset ID field enter ecommerce. Leave the other options at their default values (Data Location, Default table Expiration).
Click Create dataset.
Task 2. Troubleshooting CREATE TABLE statements
Your data analyst team has provided you with the below query statements designed to create a permanent table in your new ecommerce dataset. Unfortunately they're not working properly.
Diagnose why each of the queries is broken and offer a solution.
Rules for creating tables with SQL in BigQuery
Read through these create table rules which you will use as your guide when fixing broken queries:
Either the specified column list or inferred columns from a query_statement (or both) must be present.
When both the column list and the as query_statement clause are present, BigQuery ignores the names in the as query_statement clause and matches the columns with the column list by position.
When the as query_statement clause is present and the column list is absent, BigQuery determines the column names and types from the as query_statement clause.
Column names must be specified either through the column list or as query_statement clause.
Duplicate column names are not allowed.
Query 1: Columns, columns, columns
Add this query in the SQL query EDITOR, then Run the query, diagnose the error, and answer the questions that follow:
#standardSQL
# copy one day of ecommerce data to explore
CREATE OR REPLACE TABLE ecommerce.all_sessions_raw_20170801
OPTIONS(
description="Raw data from analyst team into our dataset for 08/01/2017"
) AS
SELECT fullVisitorId, * FROM `data-to-insights.ecommerce.all_sessions_raw`
WHERE date = '20170801' #56,989 records
;
Error: CREATE TABLE has columns with duplicate name fullVisitorId at [8:2]
Which one of the create table rules is violated in the above query?
Query 2: Columns revisited
Add this query in the SQL query EDITOR, then Run the query, diagnose the error, and answer the questions that follow:
#standardSQL
# copy one day of ecommerce data to explore
CREATE OR REPLACE TABLE ecommerce.all_sessions_raw_20170801
#schema
(
fullVisitorId STRING OPTIONS(description="Unique visitor ID"),
channelGrouping STRING OPTIONS(description="Channel e.g. Direct, Organic, Referral...")
)
OPTIONS(
description="Raw data from analyst team into our dataset for 08/01/2017"
) AS
SELECT * FROM `data-to-insights.ecommerce.all_sessions_raw`
WHERE date = '20170801' #56,989 records
;
Error: The number of columns in the column definition list does not match the number of columns produced by the query at [6:1]
Which one of the create table rules is violated in the above query?
Note: You cannot specify a schema of fields for a new table which does not match the number of columns returned by the query statement. In the above a two column schema was specified with fullVisitorId and channelGrouping but in the query statement all columns returned (\*) was specified.
Query 3: It's valid! Or is it?
Add this query in the SQL query EDITOR, then Run the query, diagnose the error, and answer the questions that follow:
#standardSQL
# copy one day of ecommerce data to explore
CREATE OR REPLACE TABLE ecommerce.all_sessions_raw_20170801
#schema
(
fullVisitorId STRING OPTIONS(description="Unique visitor ID"),
channelGrouping STRING OPTIONS(description="Channel e.g. Direct, Organic, Referral...")
)
OPTIONS(
description="Raw data from analyst team into our dataset for 08/01/2017"
) AS
SELECT fullVisitorId, city FROM `data-to-insights.ecommerce.all_sessions_raw`
WHERE date = '20170801' #56,989 records
;
Valid: This query will process 1.05 GB when run.
Remember Rule #2: When both the column list and the as query_statement clause are present, BigQuery ignores the names in the as query_statement clause and matches the columns with the column list by position.
Query 4: The gatekeeper
Run the below query in the SQL query EDITOR, then diagnose the error and answer the questions that follow:
#standardSQL
# copy one day of ecommerce data to explore
CREATE OR REPLACE TABLE ecommerce.all_sessions_raw_20170801
#schema
(
fullVisitorId STRING NOT NULL OPTIONS(description="Unique visitor ID"),
channelGrouping STRING NOT NULL OPTIONS(description="Channel e.g. Direct, Organic, Referral..."),
totalTransactionRevenue INT64 NOT NULL OPTIONS(description="Revenue * 10^6 for the transaction")
)
OPTIONS(
description="Raw data from analyst team into our dataset for 08/01/2017"
) AS
SELECT fullVisitorId, channelGrouping, totalTransactionRevenue FROM `data-to-insights.ecommerce.all_sessions_raw`
WHERE date = '20170801' #56,989 records
;
Valid: This query will process 907.52 MB when run.
Fix and re-run the modified query to confirm it executes successfully.
Query 5: Working as intended
Run this query in the SQL query EDITOR, then diagnose the error and answer the questions that follow:
#standardSQL
# copy one day of ecommerce data to explore
CREATE OR REPLACE TABLE ecommerce.all_sessions_raw_20170801
#schema
(
fullVisitorId STRING NOT NULL OPTIONS(description="Unique visitor ID"),
channelGrouping STRING NOT NULL OPTIONS(description="Channel e.g. Direct, Organic, Referral..."),
totalTransactionRevenue INT64 OPTIONS(description="Revenue * 10^6 for the transaction")
)
OPTIONS(
description="Raw data from analyst team into our dataset for 08/01/2017"
) AS
SELECT fullVisitorId, channelGrouping, totalTransactionRevenue FROM `data-to-insights.ecommerce.all_sessions_raw`
WHERE date = '20170801' #56,989 records
;
Browse your ecommerce dataset panel to confirm the all_sessions_raw_(1) is present.
Why is the full table name not showing?
Answer: The table suffix 20170801 is automatically partitioned by day. If we created more tables for other days, the all_sessions_raw_(N) would increment by N distinct days of data. There is another lab that explores different ways of partitioning your data tables.
Query 6: Your turn to practice
Goal: In the SQL query Editor, create a new permanent table that stores all the transactions with revenue for August 1st, 2017.
Use the below rules as a guide:
Create a new table in your ecommerce dataset titled revenue_transactions_20170801. Replace the table if it already exists.
Source your raw data from the data-to-insights.ecommerce.all_sessions_raw table.
Divide the revenue field by 1,000,000 and store it as a FLOAT64 instead of an INTEGER.
Only include transactions with revenue in your final table (hint: use a WHERE clause).
Only include transactions on 20170801.
Include these fields:
fullVisitorId as a REQUIRED string field.
visitId as a REQUIRED string field (hint: you will need to type convert).
channelGrouping as a REQUIRED string field.
totalTransactionRevenue as a FLOAT64 field.
Add short descriptions for the above four fields by referring to the schema.
Be sure to deduplicate records that have the same fullVisitorId and visitId (hint: use DISTINCT).
/*
write the answer to the above prompt in BigQuery and compare it to the answer below
*/
Possible answer:
#standardSQL
# copy one day of ecommerce data to explore
CREATE OR REPLACE TABLE ecommerce.revenue_transactions_20170801
#schema
(
fullVisitorId STRING NOT NULL OPTIONS(description="Unique visitor ID"),
visitId STRING NOT NULL OPTIONS(description="ID of the session, not unique across all users"),
channelGrouping STRING NOT NULL OPTIONS(description="Channel e.g. Direct, Organic, Referral..."),
totalTransactionRevenue FLOAT64 NOT NULL OPTIONS(description="Revenue for the transaction")
)
OPTIONS(
description="Revenue transactions for 08/01/2017"
) AS
SELECT DISTINCT
fullVisitorId,
CAST(visitId AS STRING) AS visitId,
channelGrouping,
totalTransactionRevenue / 1000000 AS totalTransactionRevenue
FROM `data-to-insights.ecommerce.all_sessions_raw`
WHERE date = '20170801'
AND totalTransactionRevenue IS NOT NULL #XX transactions
;
After successfully running the query, confirm in your ecommerce dataset that the new table is present name as revenue_transactions_20170801 and select it.
Confirm the schema against the below example. Note the field types, required, and optional description:
Handling upstream source data updates
What are ways to overcome stale data?
There are two ways to overcome stale data in reporting tables:
Use logical views to re-run a stored query each time the view is selected
In the remainder of this lab you will focus on how to create logical views.
Task 3. Creating views
Views are saved queries that are run each time the view is called. In BigQuery, views are logical and not materialized. Only the query is stored as part of the view -- not the underlying data.
Query the latest 100 transactions
Copy and paste the below query and execute it in BigQuery:
#standardSQL
SELECT DISTINCT
date,
fullVisitorId,
CAST(visitId AS STRING) AS visitId,
channelGrouping,
totalTransactionRevenue / 1000000 AS totalTransactionRevenue
FROM `data-to-insights.ecommerce.all_sessions_raw`
WHERE totalTransactionRevenue IS NOT NULL
ORDER BY date DESC # latest transactions
LIMIT 100
;
Scan through for filter the results.
What was the latest transaction above $2,000?
Answer:
date
fullVisitorId
visitId
channelGrouping
totalTransactionRevenue
20170801
9947542428111966715
1501608078
Referral
2934.61
If new records were added to this public ecommerce dataset, the latest transaction would also update.
To save time and enable better organization and collaboration, you can save your common reporting queries as views as demonstrated below:
#standardSQL
CREATE OR REPLACE VIEW ecommerce.vw_latest_transactions
AS
SELECT DISTINCT
date,
fullVisitorId,
CAST(visitId AS STRING) AS visitId,
channelGrouping,
totalTransactionRevenue / 1000000 AS totalTransactionRevenue
FROM `data-to-insights.ecommerce.all_sessions_raw`
WHERE totalTransactionRevenue IS NOT NULL
ORDER BY date DESC # latest transactions
LIMIT 100
;
Note: It is often difficult to know whether or not you are SELECTing from a Table or a View by just looking at the name. A simple convention is to prefix the view name with vw_ or add a suffix like _vw or _view.
You can also give your view a description and labels using OPTIONS. Copy and paste the below query and execute it in BigQuery:
#standardSQL
CREATE OR REPLACE VIEW ecommerce.vw_latest_transactions
OPTIONS(
description="latest 100 ecommerce transactions",
labels=[('report_type','operational')]
)
AS
SELECT DISTINCT
date,
fullVisitorId,
CAST(visitId AS STRING) AS visitId,
channelGrouping,
totalTransactionRevenue / 1000000 AS totalTransactionRevenue
FROM `data-to-insights.ecommerce.all_sessions_raw`
WHERE totalTransactionRevenue IS NOT NULL
ORDER BY date DESC # latest transactions
LIMIT 100
;
Find the newly created vw_latest_transactions table in your ecommerce dataset and select it.
Select the Details tab.
Confirm your view Description and Labels are properly showing in the BigQuery UI.
You can also view the query that defines the view on the Details page. This is useful for understanding the logic of views you or your team created.
Now run this query to create a new view:
#standardSQL
# top 50 latest transactions
CREATE VIEW ecommerce.vw_latest_transactions # CREATE
OPTIONS(
description="latest 50 ecommerce transactions",
labels=[('report_type','operational')]
)
AS
SELECT DISTINCT
date,
fullVisitorId,
CAST(visitId AS STRING) AS visitId,
channelGrouping,
totalTransactionRevenue / 1000000 AS totalTransactionRevenue
FROM `data-to-insights.ecommerce.all_sessions_raw`
WHERE totalTransactionRevenue IS NOT NULL
ORDER BY date DESC # latest transactions
LIMIT 50
;
You'll likely receive an error if you have already created the view before. Can you see why?
Answer: The view creation statement was updated to simply be CREATE instead of CREATE OR REPLACE which will not let you overwrite existing tables or views if they already exist. A third option, CREATE VIEW IF NOT EXISTS, will allow you to only create if the table or view doesn't exist or else it will skip the creation and not error.
View Creation: Your turn to practice
Scenario: Your anti-fraud team has asked you to create a report that lists the 10 most recent transactions that have an order amount of 1,000 or more for them to review manually.
Task: Create a new view that returns all the most recent 10 transactions with revenue greater than 1,000 on or after January 1st, 2017.
Use these rules as a guide:
Create a new view in your ecommerce dataset titled "vw_large_transactions". Replace the view if it already exists.
Give the view a description "large transactions for review".
Give the view a label [("org_unit", "loss_prevention")].
Source your raw data from the data-to-insights.ecommerce.all_sessions_raw table.
Divide the revenue field by 1,000,000.
Only include transactions with revenue greater than or equal to 1,000
Only include transactions on or after 20170101 ordered by most recent first.
Only include currencyCode = 'USD'.
Return these fields:
date
fullVisitorId
visitId
channelGrouping
totalTransactionRevenue AS revenue
currencyCode
v2ProductName
Be sure to deduplicate records (hint: use DISTINCT).
You try
/*
write the answer to the above prompt in BigQuery and compare it to the answer given below
*/
Possible solution:
#standardSQL
CREATE OR REPLACE VIEW ecommerce.vw_large_transactions
OPTIONS(
description="large transactions for review",
labels=[('org_unit','loss_prevention')]
)
AS
SELECT DISTINCT
date,
fullVisitorId,
visitId,
channelGrouping,
totalTransactionRevenue / 1000000 AS revenue,
currencyCode
#v2ProductName
FROM `data-to-insights.ecommerce.all_sessions_raw`
WHERE
(totalTransactionRevenue / 1000000) > 1000
AND currencyCode = 'USD'
ORDER BY date DESC # latest transactions
LIMIT 10
;
Note: You need to repeat the division in the WHERE clause because you cannot use aliased field names as filters.
Extra credit
Scenario: Your anti-fraud department is grateful for the query and they are monitoring it daily for suspicious orders. They have now asked you to include a sample of the products that are part of each order along with the results you returned previously.
Using the BigQuery string aggregation function STRING_AGG and the v2ProductName field, modify your previous query to return 10 of the product names in each order, listed alphabetically.
Possible solution:
#standardSQL
CREATE OR REPLACE VIEW ecommerce.vw_large_transactions
OPTIONS(
description="large transactions for review",
labels=[('org_unit','loss_prevention')]
)
AS
SELECT DISTINCT
date,
fullVisitorId,
visitId,
channelGrouping,
totalTransactionRevenue / 1000000 AS totalTransactionRevenue,
currencyCode,
STRING_AGG(DISTINCT v2ProductName ORDER BY v2ProductName LIMIT 10) AS products_ordered
FROM `data-to-insights.ecommerce.all_sessions_raw`
WHERE
(totalTransactionRevenue / 1000000) > 1000
AND currencyCode = 'USD'
GROUP BY 1,2,3,4,5,6
ORDER BY date DESC # latest transactions
LIMIT 10
Note the two additions here to aggregate the list of products in each order with STRING_AGG() and, since you're performing an aggregation, the necessary GROUP BY is added for the other fields.
Using SESSION_USER() in views for limiting data access
Scenario: Your data team lead has asked you to come up with a way to limit who in your organization can see the data returned by the view you just created. Order information is especially sensitive and needs to be shared only with users that have a need to see such information.
Task: Modify the view you created earlier to only allow logged in users with a qwiklabs.net session domain to be able to see the data in the underlying view. (Note: You will be creating specific user group whitelists in a later lab on access; for now you are validating based on the session user's domain).
To view your own session login information, run the below query that uses SESSION_USER():
#standardSQL
SELECT
SESSION_USER() AS viewer_ldap;
Modify the below query to add an additional filter to only allow users in the qwiklabs.net domain to see view results:
#standardSQL
SELECT DISTINCT
SESSION_USER() AS viewer_ldap,
REGEXP_EXTRACT(SESSION_USER(), r'@(.+)') AS domain,
date,
fullVisitorId,
visitId,
channelGrouping,
totalTransactionRevenue / 1000000 AS totalTransactionRevenue,
currencyCode,
STRING_AGG(DISTINCT v2ProductName ORDER BY v2ProductName LIMIT 10) AS products_ordered
FROM `data-to-insights.ecommerce.all_sessions_raw`
WHERE
(totalTransactionRevenue / 1000000) > 1000
AND currencyCode = 'USD'
# add filter here
GROUP BY 1,2,3,4,5,6,7,8
ORDER BY date DESC # latest transactions
LIMIT 10
Possible solution:
#standardSQL
SELECT DISTINCT
SESSION_USER() AS viewer_ldap,
REGEXP_EXTRACT(SESSION_USER(), r'@(.+)') AS domain,
date,
fullVisitorId,
visitId,
channelGrouping,
totalTransactionRevenue / 1000000 AS totalTransactionRevenue,
currencyCode,
STRING_AGG(DISTINCT v2ProductName ORDER BY v2ProductName LIMIT 10) AS products_ordered
FROM `data-to-insights.ecommerce.all_sessions_raw`
WHERE
(totalTransactionRevenue / 1000000) > 1000
AND currencyCode = 'USD'
AND REGEXP_EXTRACT(SESSION_USER(), r'@(.+)') IN ('qwiklabs.net')
GROUP BY 1,2,3,4,5,6,7,8
ORDER BY date DESC # latest transactions
LIMIT 10
Execute the above query to confirm you can see records returned.
Now, remove all domains from the IN filter REGEXP_EXTRACT(SESSION_USER(), r'@(.+)') IN (''), execute the query again, and confirm you see zero records returned.
Re-create and replace the vw_large_transactions view with the new query above. As an additional OPTIONS parameter, add an expiration_timestamp for the entire view to be 90 days from now:
#standardSQL
CREATE OR REPLACE VIEW ecommerce.vw_large_transactions
OPTIONS(
description="large transactions for review",
labels=[('org_unit','loss_prevention')],
expiration_timestamp=TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL 90 DAY)
)
AS
#standardSQL
SELECT DISTINCT
SESSION_USER() AS viewer_ldap,
REGEXP_EXTRACT(SESSION_USER(), r'@(.+)') AS domain,
date,
fullVisitorId,
visitId,
channelGrouping,
totalTransactionRevenue / 1000000 AS totalTransactionRevenue,
currencyCode,
STRING_AGG(DISTINCT v2ProductName ORDER BY v2ProductName LIMIT 10) AS products_ordered
FROM `data-to-insights.ecommerce.all_sessions_raw`
WHERE
(totalTransactionRevenue / 1000000) > 1000
AND currencyCode = 'USD'
AND REGEXP_EXTRACT(SESSION_USER(), r'@(.+)') IN ('qwiklabs.net')
GROUP BY 1,2,3,4,5,6,7,8
ORDER BY date DESC # latest transactions
LIMIT 10;
Note: The expiration_timestampoption can also be applied to permanent tables.
Confirm with the below SELECT statement you can see the data returned in the view (given your domain access) and the expiration timestamp in the view details.
#standardSQL
SELECT * FROM ecommerce.vw_large_transactions;
When you have completed your lab, click End Lab. Google Skills removes the resources you’ve used and cleans the account for you.
You will be given an opportunity to rate the lab experience. Select the applicable number of stars, type a comment, and then click Submit.
The number of stars indicates the following:
1 star = Very dissatisfied
2 stars = Dissatisfied
3 stars = Neutral
4 stars = Satisfied
5 stars = Very satisfied
You can close the dialog box if you don't want to provide feedback.
For feedback, suggestions, or corrections, please use the Support tab.
Copyright 2026 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.
Moduły tworzą projekt Google Cloud i zasoby na określony czas.
Moduły mają ograniczenie czasowe i nie mają funkcji wstrzymywania. Jeśli zakończysz moduł, musisz go zacząć od początku.
Aby rozpocząć, w lewym górnym rogu ekranu kliknij Rozpocznij moduł.
Użyj przeglądania prywatnego
Skopiuj podaną nazwę użytkownika i hasło do modułu.
Kliknij Otwórz konsolę w trybie prywatnym.
Zaloguj się w konsoli
Zaloguj się z użyciem danych logowania do modułu. Użycie innych danych logowania może spowodować błędy lub naliczanie opłat.
Zaakceptuj warunki i pomiń stronę zasobów przywracania.
Nie klikaj Zakończ moduł, chyba że właśnie został przez Ciebie zakończony lub chcesz go uruchomić ponownie, ponieważ spowoduje to usunięcie wyników i projektu.
Ta treść jest obecnie niedostępna
Kiedy dostępność się zmieni, wyślemy Ci e-maila z powiadomieniem
Świetnie
Kiedy dostępność się zmieni, skontaktujemy się z Tobą e-mailem
Jeden moduł, a potem drugi
Potwierdź, aby zakończyć wszystkie istniejące moduły i rozpocząć ten
Aby uruchomić moduł, użyj przeglądania prywatnego
Najlepszym sposobem na uruchomienie tego laboratorium jest użycie okna incognito lub przeglądania prywatnego. Dzięki temu unikniesz konfliktu między swoim kontem osobistym a kontem do nauki, co mogłoby spowodować naliczanie dodatkowych opłat na koncie osobistym.
This lab focuses on how to create new permanent reporting tables and logical reviews from an existing ecommerce dataset.
Czas trwania:
Konfiguracja: 0 min
·
Dostęp na 90 min
·
Ukończono w 60 min