2013-10-29 42 views
0

我的表結構:不是訂購的所有列值

古蘭經主

enter image description here

QuranPrayed:

enter image description here

我想根據我的時間戳,使結果。

表示希望根據時間戳記計算sipara。

對於我提出以下查詢:

SELECT qm.sipara, Prayed = COUNT(qp.Sipara) 
FROM QuranMaster qm LEFT JOIN QuranPrayed qp ON qp.sipara=qm.sipara 
where qp.TimeStamp between '2013-10-27 19:59:00.000' and '2013-10-28 20:00:00.000' 
GROUP BY qm.sipara,qm.OrderID order by qm.OrderID 

但其0次不給結果祈禱siparas。

其給予如下:

enter image description here

還應該表現出sipara4爲0,sipara5爲0 ...等。

請幫幫我。

+0

您是否嘗試過使用COUNT(ISNULL(qp.Sipara,0))? –

+0

或嘗試在連接上添加「LEFT JOIN QuranPrayed qp ON 1 = 1 AND qp.sipara = qm.sipara」 –

回答

3

試試這個

SELECT qm.sipara, 
     Prayed = COUNT(qp.Sipara) 
FROM QuranMaster qm LEFT JOIN 
    QuranPrayed qp ON (qp.sipara = qm.sipara AND qp.TimeStamp >= '2013-10-27 19:59:00.000' AND qp.TimeStamp <= '2013-10-28 20:00:00.000') 
GROUP BY qm.sipara,qm.OrderID 
ORDER BY qm.OrderID 

基本上,你的WHERE子句過濾掉行,因此將您的WHERE子句中的時間戳條件移至LEFT JOIN子句中,意味着您可以包含QuranMaster中的所有行,然後只包含QuranPrayed中符合時間戳的記錄的計數p條件,否則那些不符合時間戳條件的記錄不會加入,因此不包括在計數中

+0

Thanx,完美的查詢 –

1

使用SiparaCOUNT(...)

SELECT qm.sipara, 
     Prayed = COUNT(qm.Sipara) 
FROM QuranMaster qm 
     LEFT JOIN QuranPrayed qp 
      ON qp.sipara=qm.sipara 
where qp.TimeStamp between '2013-10-27 19:59:00.000' and '2013-10-28 20:00:00.000' 
GROUP BY qm.sipara,qm.OrderID 
ORDER BY qm.OrderID 

我也建議不使用BETWEEN>=<QuranMaster而不是QuranPrayed領域:

SELECT qm.sipara, 
     Prayed = COUNT(qm.Sipara) 
FROM QuranMaster qm 
     LEFT JOIN QuranPrayed qp 
      ON qp.sipara=qm.sipara 
where qp.TimeStamp >='2013-10-27 19:59:00.000' 
     and qp.TimeStamp < '2013-10-28 20:00:00.000' 
GROUP BY qm.sipara,qm.OrderID 
ORDER BY qm.OrderID 
+0

沒有獲得所有sipara –

+0

爲什麼不能使用'BETWEEN'? –

+0

@DStanley他們倆都沒有工作 –

1

你的WHERE子句過濾掉父行是沒有孩子排。此舉條件的JOIN:

SELECT qm.sipara, 
     Prayed 
FROM QuranMaster qm 
LEFT JOIN QuranPrayed qp 
    ON qp.sipara=qm.sipara 
     AND qp.TimeStamp between '2013-10-27 19:59' and '2013-10-28 20:00' 
GROUP BY qm.sipara, 
     qm.OrderID 
ORDER BY qm.OrderID 

還是做分組在一個子查詢:

SELECT qm.sipara, 
     Prayed = COUNT(qm.Sipara) 
FROM QuranMaster qm 
LEFT JOIN (
    SELECT sipara, 
      Prayed = COUNT(*) 
    FROM QuranPrayed 
    WHERE TimeStamp between '2013-10-27 19:59' and '2013-10-28 20:00' 
    GROUP BY qm.sipara) QP 
    ON qp.sipara=qm.sipara 
ORDER BY qm.OrderID 
+0

獲取所有sipara ...但錯誤的計數...所有日期的sipara計數 –

2

問題是您的時間戳記之間的數據是要刪除您想要求和的記錄。首先完成總和,然後從主控制器上離開。

SELECT 
    qm.sipara 
, vsum.Prayed 
From QuranMaster qm 
LEFT JOIN 
(
    Select 
     qp.sipara 
    , Prayed = COUNT(qp.Sipara) 
    From QuranPrayed qp 
    GROUP BY qp.sipara 
) vsum 
ON vsum.sipara=qp.sipara