2015-05-26 134 views
1

我有這樣的代碼從表中選擇行,但我需要讓他返回所有行或平均所有行的總和。我試圖把代碼放在其他選擇像總和(選擇)內選擇,但它不工作,任何想法如何使其工作?對不起,沒有太多的信息。現在它打印25行。我需要讓它返回1行,就像sum(按時)和avg(實際)。我的意思是總結所有25行的ontime列和avg實際列。SQL選擇總和/平均所有行

SELECT AVG(CASE WHEN a.ontime = 'on time' THEN 100 ELSE 0 END)*COUNT(a.country) AS ontime 
    ,AVG(CASE WHEN a.accuracy = 'accurate' THEN 100 ELSE 0 END) AS actual 
    ,COUNT(a.country) AS task_count 

FROM 
    bstplanning.dbo.sc_data a 
    INNER JOIN bstplanning.dbo.users 
    ON a.user_id = bstplanning.dbo.users.user_id  

WHERE 
    a.date >= '2015-04-01 00:00:00.000' AND a.date <= '2015-04-30 00:00:00.000' AND a.actual > 0 AND 
    ((a.ontime='on time' OR a.ontime = 'late') OR (a.accuracy='accurate' OR a.accuracy = 'error')) 
    and bstplanning.dbo.users.split='Rep' 
    and bstplanning.dbo.users.user_surname='user' 
GROUP BY 
    a.country 
    ,a.client 
    ,a.task_group 
    ,frequency 
    ,a.track 
+0

'它不是working'是不夠的。給我們詳細信息。 – kebs

+0

用樣品數據和所需結果編輯您的問題。我還注意到代碼是SQL Server代碼,所以我刪除了MySQL標記。 –

+0

已編輯。它更清楚嗎? – Macb3th

回答

1

您可以編寫外部查詢和您的查詢的內層查詢..

SELECT Sum(Ontime) AS Ontime 
    ,AVG(actual) AS Actual 
    ,Sum(task_count) AS task_count 
FROM (
    SELECT AVG(CASE 
       WHEN a.ontime = 'on time' 
        THEN 100 
       ELSE 0 
       END) * COUNT(a.country) AS ontime 
     ,AVG(CASE 
       WHEN a.accuracy = 'accurate' 
        THEN 100 
       ELSE 0 
       END) AS actual 
     ,COUNT(a.country) AS task_count 
    FROM bstplanning.dbo.sc_data a 
    INNER JOIN bstplanning.dbo.users ON a.user_id = bstplanning.dbo.users.user_id 
    WHERE a.DATE >= '2015-04-01 00:00:00.000' 
     AND a.DATE <= '2015-04-30 00:00:00.000' 
     AND a.actual > 0 
     AND (
      (
       a.ontime = 'on time' 
       OR a.ontime = 'late' 
       ) 
      OR (
       a.accuracy = 'accurate' 
       OR a.accuracy = 'error' 
       ) 
      ) 
     AND bstplanning.dbo.users.split = 'Rep' 
     AND bstplanning.dbo.users.user_surname = 'user' 
    GROUP BY a.country 
     ,a.client 
     ,a.task_group 
     ,frequency 
     ,a.track 
    ) Drive 
+0

謝謝。當我試圖這樣做,但它不適合我時,現在它工作。非常感謝你。 – Macb3th