SORU
27 EYLÜL 2010, PAZARTESİ


Grup, her grupta ilk satır seçmek?

Başlıktan da anlaşılacağı gibi, satır GROUP BY ile gruplandırılmış her kümesindeki ilk satırı seçmek istiyorum.

Eğer purchases bir tablo var, özellikle bu gibi görünüyor:

SELECT * FROM purchases;
id | customer | total
--- ---------- ------
 1 | Joe      | 5
 2 | Sally    | 3
 3 | Joe      | 2
 4 | Sally    | 1

En büyük alım (total) customer her tarafından yapılan id sorgulamak istiyorum. Şöyle bir şey:

SELECT FIRST(id), customer, FIRST(total)
FROM  purchases
GROUP BY customer
ORDER BY total DESC;
FIRST(id) | customer | FIRST(total)
---------- ---------- -------------
        1 | Joe      | 5
        2 | Sally    | 3

CEVAP
27 EYLÜL 2010, PAZARTESİ


Oracle 8i SQL Server 2005 , PostgreSQL 8.4 , DB2 , Firebird 2.1 Alma, Sybase, Vertica:

WITH summary AS (
    SELECT p.id, 
           p.customer, 
           p.total, 
           ROW_NUMBER() OVER(PARTITION BY p.customer 
                                 ORDER BY p.total DESC) AS rk
      FROM PURCHASES p)
SELECT s.*
  FROM summary s
 WHERE s.rk = 1

Herhangi bir veritabanı tarafından desteklenen

Ama mantık bağları kırmak için eklemek gerekir:

  SELECT MIN(x.id),  -- change to MAX if you want the highest
         x.customer, 
         x.total
    FROM PURCHASES x
    JOIN (SELECT p.customer,
                 MAX(total) AS max_total
            FROM PURCHASES p
        GROUP BY p.customer) y ON y.customer = x.customer
                              AND y.max_total = x.total
GROUP BY x.customer, x.total

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • ASUS North America

    ASUS North A

    12 AĞUSTOS 2008
  • RFS Dan

    RFS Dan

    22 Temmuz 2014
  • RiceBunny

    RiceBunny

    16 ŞUBAT 2006