2017-07-16 67 views
0

我有以下查詢:計算列

SELECT 
a.source, 
TotalCount, 
ActiveCount 
FROM 
(
    SELECT COUNT(*) AS TotalCount, a.source 
    FROM internship a 
    GROUP BY a.source 
) AS A 
join 
(
    SELECT COUNT(*) AS ActiveCount, b.source 
    FROM internship b 
    WHERE b.int_lastdate > CURDATE() AND b.status LIKE 'Published' 
    GROUP BY b.source 
) AS B 
    ON A.source = B.source 

上面的查詢給了我這樣的結果:

enter image description here

我想補充另一列這將是「ExpiredCount = TotalCount - ActiveCount

我該如何達到這個目標?

回答

1

戈登的答案可能是什麼,我會希望看作是繼承別人代碼的DBA。但是我們實際上可以避免使用子查詢,只需寫下以下內容:

SELECT 
    source, 
    COUNT(*) AS TotalCount, 
    SUM(CASE WHEN int_lastdate > CURDATE() AND status LIKE 'Published' 
      THEN 1 ELSE 0 END) AS ActiveCount, 
    COUNT(*) - SUM(CASE WHEN int_lastdate > CURDATE() AND status LIKE 'Published' 
         THEN 1 ELSE 0 END) AS ExpiredCount 
FROM internship 
GROUP BY source 
+0

謝謝!這個查詢也適用於創建視圖。 – Rohit

2

你只需要一個表達式。但是,您可以簡化您的查詢:

select i.source, i.TotalCount, i.ActiveCount, 
     (i.TotalCount - i.ActiveCount) as ExpiredCount 
from (select i.source, count(*) as TotalCount, i.source, 
      sum(i.int_lastdate > curdate() and i.status like 'Published') as ActiveCount 
     from internship i 
     group by i.source 
    ) i; 

注:

  • 表的別名應該是表名的縮寫,所以他們很容易閱讀。
  • 對於此查詢,您不需要join,只是有條件的聚合。
  • 過度使用反引號是不必要的,使查詢更難寫。
  • 您的問題的答案是一個簡單的表達式。

編輯:

如果你想用這個作爲一個視圖,你不能有FROM子句中的子查詢(MySQL的限制):

 select i.source, count(*) as TotalCount, i.source, 
      sum(i.int_lastdate > curdate() and i.status like 'Published') as ActiveCount, 
      (count(*) - sum(i.int_lastdate > curdate() and i.status like 'Published')) as ExpiredCount 
     from internship i 
     group by i.source 
+0

謝謝!查詢工作,但我無法將查詢保存爲「查看」。 – Rohit

+0

@Rohit。 。 。您無法將原始查詢保存爲視圖。這個問題甚至沒有提到。 –