SELECT
(case when tableA.gender = 'Male' then tableB.X) as Male,
(case when tableA.gender = 'Female' then tableB.X) as Female
...
FROM (MANY TABLES JOINT)
...
GROUP BY tableB.X
ORDER BY count(*) DESC
我正在尝试通过查询另一列(tableB.X)是“男性”还是“女性”来基于一个字段(column_name)返回两列。我该怎么做呢?我仍然需要在DESC中订购这两个列。谢谢。
每行返回一个值和一个性别(2列)。我试图根据性别将值拆分为两列,然后按每个拆分列的计数降序显示..
即。输入表:
value Gender
----- ------
AAA Male
BBB Female
AAA Male
CCC Male
AAA Female
BBB Female
即。输出表:
Rank Male Female
---- ---- ------
1 AAA BBB (AAA because it has 2 male occurences, BBB has 2 female occurences)
2 CCC AAA (1 occurence each for male and female, ordered descending order)
我也不知道有多少不同的值,所以SQL必须为我做计算。我可以使用两个查询获得结果,使用WHERE gender = male和WHERE gender = female但我想知道我是否可以在一个查询中执行此操作..谢谢!
答案 0 :(得分:0)
我认为使用UNION
语句可以做到这一点。以下未经过测试:
SELECT
tableB.X as Male,
'' as Female
FROM
...
tableB JOIN tableA
...
WHERE tableA.gender = 'male'
UNION
SELECT
'' as Male,
tableB.X as Female
FROM
...
tableB JOIN tableA
...
WHERE tableA.gender = 'female'
您也可以使用''
代替空字符串NULL
。