2015-11-29 56 views
0

我有兩個表像以下:SQL - 試圖找出1組的超過0的比率?

CouponTable

  • ID
  • IsAvailable
  • COwnerId

CouponOwner

  • COwnerId
  • COwnerName

下面是情形:我需要計算IsAvailable的速率(1或0)對於每個優惠券所有者?我找不到我可以先由COwners對它進行分組,然後找到每個分組的速率。

我想這下面的SQL代碼,這是具體的只對業主,這個效果很好,但我不應該給每個擁有者的標識的,我需要做的更通用的方法。

SELECT 
    C.COwnerId, 
    O.COwnerName, 
    (select count(*) from CouponTable where COwnerId = 105 and IsAvailable = 1) * 100 /(select count(*) from CouponTable where COwnerId = 105) as Rate 
FROM 
    CouponTable AS C 
     JOIN 
    CouponOwner AS O ON C.COwnerId = O.COwnerId where C.COwnerId = 105 
GROUP BY C.COwnerId 
ORDER BY Rate DESC; 

這將返回如下:

105,加雷斯·威爾遜,21.9229

回答

1

您可以使用相關子查詢:

SELECT 
    C.COwnerId, 
    O.COwnerName, 
    (SELECT COUNT(*) 
    FROM CouponTable 
    WHERE COwnerId = c.COwnerId AND IsAvailable = 1) * 100/
    (SELECT count(*) 
    FROM CouponTable 
    WHERE COwnerId = c.COwnerId) AS Rate 
FROM 
    CouponTable AS C 
INNER JOIN 
    CouponOwner AS O ON C.COwnerId = O.COwnerId 
GROUP BY C.COwnerId 
ORDER BY Rate DESC; 

這樣,你只需要替換特定COwnerId的值,即105,該字段的值來自外部查詢,即c.COwnerId

Demo here

+0

這個方案看起來像它的工作,但是當我在我的機器上運行它,它不返回任何結果,它口口聲聲說在工作臺的輸出窗口中的「運行」。 –

0

您可以用CouponOwner表加入CouponTable,並使用GROUP BY查詢用SUM和COUNT:

SELECT 
    ID, 
    CouponOwner, 
    (SUM(IsAvailable)/COUNT(*))*100 As Rate 
FROM 
    CouponTable ct INNER JOIN CouponOwner co 
    ON ct.CouponOwnner=co.CoOwnerID 
GROUP BY 
    ID, 
    CouponOwner 
ORDER BY 
    (SUM(IsAvailable)/COUNT(*))*100 DESC 

SUM(IsAvailabe)的優惠券供業主數目和COUNT(*)是爲業主所有優惠券的數量。