← Back to PostgreSQL Course | Chapter 7: Aggregations & Grouping | Lesson 4 of 7

Aggregates के साथ DISTINCT

COUNT(DISTINCT col) और similar forms सिर्फ unique values aggregate करते हैं।
Syntax
sql
SELECT COUNT(DISTINCT column), SUM(DISTINCT column)
FROM table_name;

Aggregates के साथ DISTINCT

COUNT(DISTINCT city) unique cities count करता है, और SUM(DISTINCT x) हर अलग value एक बार add करता है।

PostgreSQL में आप string_agg(DISTINCT name, ', ') और array_agg(DISTINCT x) जैसे aggregate functions भी इस्तेमाल कर सकते हैं। Aggregates के अंदर DISTINCT, SELECT DISTINCT से अलग है, जो duplicate rows remove करता है।

Note: COUNT(DISTINCT x) unique visitors count करने का एक common तरीका है।

उदाहरण: DISTINCT with aggregates

sql
CREATE TABLE visits (id INTEGER PRIMARY KEY, visitor TEXT, page TEXT);
INSERT INTO visits VALUES (1,'ada','home'),(2,'bob','home'),(3,'ada','pricing'),(4,'ada','home'),(5,'cy','pricing');
SELECT COUNT(*) AS hits, COUNT(DISTINCT visitor) AS unique_visitors FROM visits;
SELECT page, COUNT(*) AS hits, COUNT(DISTINCT visitor) AS unique_visitors FROM visits GROUP BY page ORDER BY page;

-- Output:
-- hits | unique_visitors
-- 5 | 3
-- page | hits | unique_visitors
-- home | 3 | 2
-- pricing | 2 | 2
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. SELECT DISTINCT को COUNT(DISTINCT) से confuse करना
  2. bad joins hide करने के लिए DISTINCT इस्तेमाल करना
  3. यह भूल जाना कि DISTINCT की एक sort या hash cost है
चैप्टर सारांश
  • COUNT(DISTINCT x) unique values count करता है
  • SUM(DISTINCT x) unique values add करता है
  • Grouped queries के अंदर काम करता है
  • SELECT DISTINCT से अलग है
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.