示例表
T1: pro_id(pk)|name T2: cus_id (pk)|name|gender T3: id (pk) | pro_id (FK)|cus_id (FK)
--------------- ------------------- ---------------------------------
p1|Fearless 1 |James|Male 1 | p1 | 1
p2|fanta 2 |Kaddy|Female 2 | p3 | 1
p3|soul mate 3 |Bob |Null 3 | p1 | 2
我需要返回订购特定产品的所有pro_id、Gender和性别计数(男性或女性数量(。波纹管是预期的结果;
pro_id|Gender|Gender_count
--------------------------
p1 |None | 5
p1 |Male | 10
p1 |Female| 8
p2 |None | 2
p2 |Male | 6
p2 |Female| 15
P3 |None | 1
.
.
我尝试了下面的代码,但没有产生预期的结果
SELECT T3.pro_id, T2.gender, (select count(*) from T3 where T3.cus_id = T2.cus_id) as count FROM T2, T3
我也和其他几个人一起尝试了下面的示例代码,但没有用
SELECT T1.pro_id, T2.gender, count(T2.gender)
FROM T1
JOIN T3 ON T1.pro_id = T3.pro_id
JOIN T2 ON T2.cus_id = T3.cus_id
GROUP BY T2.gender
您有正确的想法,但在group by
子句中缺少pro_id
。您还引用了group by
子句中不存在的表别名p
——您可能是想引用T2.gender
,就像在select
列表中一样。
SELECT T1.pro_id, T2.gender, count(T2.gender)
FROM T1
JOIN T3 ON T1.pro_id = T3.pro_id
JOIN T2 ON T2.cus_id = T3.cus_id
GROUP BY T1.pro_id, T2.gender