I have an SQL query (MSSQLSERVER) where I add columns to the result set using subqueries:
SELECT P.name,
(select count(*) from cars C where C.type = 'sports') AS sportscars,
(select count(*) from cars C where C.type = 'family') AS familycars,
(select count(*) from cars C where C.type = 'business') AS businesscars
FROM people P
WHERE P.id = 1;
The above query is just a test that is a little nonsense, but it works reasonably well, as I think. The query I'm actually working on contains many complex tables that only distract from the problem.
In the above example, each entry in the "people" table also contains three additional columns: "wantsSportsport", "wantsFamilycar" and "wantsBusinesscar". Now what I want to do is only make a subquery of each additional column, if the corresponding field "wants ....." in the people table is set to "true". In other words, I only want to make the first sub-collection if P.wantsSportscar is set to true for that particular person. The second and third sub-elections should work in a similar way.
So, the way this query should work is that it shows the name of a particular person and the number of available models for the types of cars that he wants to own. It may be worth noting that my final set of results will always contain only one record, namely one specific user.
It is important that if a person is not interested in a particular type of car, then the column for this type will not be included in the final result set. An example to make this clear:
If person A wants a sports car and a family car, the result will include the columns “name”, “sports cars” and “family cars”.
If person B wants a business car, the result will include the columns "name" and "business car".
IF, CASE EXISTS, . - , ? , .