Last tested: Dec 9, 2019
I want to write a correlated subquery, but I'd like to do it without using derived tables or table calculations.
We can take advantage of the fact that type: number
measures allow us to write basically any SQL in order to write a subquery. (Warning: Not all databases support correlated subqueries. These examples are written for MySQL.)
sql: (SELECT count(category) FROM table) ;;
sql: (SELECT count(category) FROM table WHERE users.email = `users.email`) ;;
sql: {% if users.email._is_selected %}
(SELECT count(category) FROM table WHERE users.email = `users.email`)
{% else %} -1 {% endif %} ;;
type: number
measure returns null.)html: {% if value == -1 %}
Please select users.email in order to use this field.
{% else %} {{value}} {% endif %} ;;
That's it! Here is the full measure definition that we have been building up to:
measure: count_categories {
label: "Count of categories for this email address"
type: number
sql:
{% if users.email._is_selected %}
(SELECT count(category) FROM table WHERE users.email = `users.email`)
{% else %}
-1
{% endif %}
;;
html:
{% if value == -1 %}
Please select users.email in order to use this field.
{% else %}
{{value}}
{% endif %}
;;
}
This content is subject to limited support.