Tek seçmek için muliple seçin mysql optimizasyon,

1 Cevap php

Bir dönemlerin (SUM (toplam)) toplam MAX seçmek gerekir nerede tablo var.

SELECT SUM(P.amount) as total FROM bank P WHERE P.ReceivedDate >= '2008-07-28' AND P.ReceivedDate <= '2008-08-31';

SELECT SUM(P.amount) as total FROM bank P WHERE P.ReceivedDate >= '2008-09-01' AND P.ReceivedDate <= '2008-09-28';

SELECT SUM(P.amount) as total FROM bank P WHERE P.ReceivedDate >= '2008-09-29' AND P.ReceivedDate <= '2008-10-26';

Ben yukarıdaki sorgular çalıştırmak ve php en yüksek toplam bulmak.

Ben nasıl bu sorgu ile grup emin değilim.

Ben MAX için tüm bu sorguyu değiştirmek için tek bir sorgu (SUM (toplam)) bekliyorum.

bana yardım edin.

1 Cevap

Gibi bir şey deneyebilirsiniz

SELECT  TOP 1
        CASE
            WHEN P.ReceivedDate BETWEEN '2008-07-28' AND '2008-08-31' THEN 1
            WHEN P.ReceivedDate BETWEEN '2008-09-01' AND '2008-09-28' THEN 2
            WHEN P.ReceivedDate BETWEEN '2008-09-29' AND '2008-10-26' THEN 3
        END,
        SUM(P.amount) Total
FROM    bank p
GROUP BY CASE
            WHEN P.ReceivedDate BETWEEN '2008-07-28' AND '2008-08-31' THEN 1
            WHEN P.ReceivedDate BETWEEN '2008-09-01' AND '2008-09-28' THEN 2
            WHEN P.ReceivedDate BETWEEN '2008-09-29' AND '2008-10-26' THEN 3
        END

HAVING  CASE 
            WHEN P.ReceivedDate BETWEEN '2008-07-28' AND '2008-08-31' THEN 1 
            WHEN P.ReceivedDate BETWEEN '2008-09-01' AND '2008-09-28' THEN 2 
            WHEN P.ReceivedDate BETWEEN '2008-09-29' AND '2008-10-26' THEN 3 
        END IS NOT NULL
ORDER BY Total DESC

ya da daha kısa bir versiyonu

SELECT  TOP 1
        SUM(amount) Total
FROM    (
            SELECT  CASE 
                        WHEN P.ReceivedDate BETWEEN '2008-07-28' AND '2008-08-31' THEN 1 
                        WHEN P.ReceivedDate BETWEEN '2008-09-01' AND '2008-09-28' THEN 2 
                        WHEN P.ReceivedDate BETWEEN '2008-09-29' AND '2008-10-26' THEN 3 
                    END GroupVal,
                    P.amount
            FROM    bank P
        ) Vals
GROUP BY Vals.GroupVal
HAVING  Vals.GroupVal IS NOT NULL
ORDER BY Total DESC