我有两个表,每个表有两列
Table 1: UserID, UserName
Table 2: UserID, rate
费率列可以取值A或B.
是否可以列出由(num of As) - (num of Bs)
排序的用户名基本上每个UserID
可以有多个As和B,我想按照(#sn的数量减去B的数量)列出UserID
答案 0 :(得分:0)
尝试使用:
SELECT t1.UserName,
(SUM(IF(t2.rate = 'A'), 1, 0) - SUM(IF(t2.rate = 'B'), 1, 0)) as temp
FROM table1 t1 INNER JOIN table2 t2
ON t1.UserID = t2.UserID
GROUP BY t1.UserID
ORDER BY temp;
答案 1 :(得分:0)
我认为这是您正在寻找的查询:
SELECT T1.UserID
,COUNT(T2A.rate) - COUNT(T2B.rate) AS [rateDiff]
FROM Table1 T1
LEFT OUTER JOIN Table2 T2A ON T2A.UserID = T1.UserID
AND T2A.rate = 'A'
LEFT OUTER JOIN Table2 T2B ON T2B.UserID = T1.UserID
AND T2B.rate = 'B'
GROUP BY T1.UserID
ORDER BY COUNT(T2A.rate) - COUNT(T2B.rate)
希望这会有所帮助,告诉我结果是不是你期望的结果。