Я писал запрос, который возвращает количество друзей-мужчин, живущих в данной стране, а затем всех друзей-женщин пользователя.
Таблица, которую я использую, выглядит следующим образом:
SELECT COUNT(gender)
FROM (SELECT friend.*
FROM friendship
JOIN user_profile AS friend ON friend.id = friendship.user_profile2_id
JOIN location ON friend.location_id = location.id
WHERE friendship.user_profile1_id = :userId AND location.current_country = "Israel"
UNION
SELECT friend.*
FROM friendship
JOIN user_profile AS friend ON friend.id = friendship.user_profile1_id
JOIN location ON friend.locationId = location.id
WHERE friendship.user_profile2_id = :userId AND location.current_country = "Israel") AS friends
GROUP BY gender
вывод должен быть 2 числа,
25
20
Я пытаюсь развернуть вывод, чтобы вместо двух столбцов
25 20
Я придумал запутанное решение, которое, как я знаю, можно улучшить
SELECT
(SELECT COUNT(*) FROM (
SELECT * FROM friendship
JOIN user_profile AS friend ON friend.id = friendship.user_profile_two.id
JOIN location ON friend.locationId = location.id
WHERE friendship.user_profile1_id = :userId AND friend.gender = "Male" AND location.current_country = "Israel"
UNION
SELECT friend.*
FROM friendship
JOIN user_profile AS friend ON friend.id = friendship.user_profile_one.id
JOIN location ON friend.locationId = location.id
WHERE friendship.user_profile2_id = :userId AND friend.gender = "Male" AND location.current_country = "Israel")) AS male_friends,
(SELECT COUNT(*) FROM (
SELECT * FROM friendship
JOIN user_profile AS friend ON friend.id = friendship.user_profile_two.id
JOIN location ON friend.locationId = location.id
WHERE friendship.user_profile1_id = :userId AND friend.gender = "Female" AND location.current_country = "Israel"
UNION
SELECT friend.*
FROM friendship
JOIN user_profile AS friend ON friend.id = friendship.user_profile_one.id
JOIN location ON friend.locationId = location.id
WHERE friendship.user_profile2_id = :userId AND friend.gender = "Female" AND location.current_country = "Israel")) AS female_friends
FROM friendship
LIMIT 1
Сводный запрос может быть потенциальным решением?
https://dbanotes.com/oracle-11g-pivot-functions-e119a8ebfdeb