Aggregates के साथ DISTINCT
COUNT(DISTINCT col) और similar forms सिर्फ unique values aggregate करते हैं।
In this page:
Syntax
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
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
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- SELECT DISTINCT को COUNT(DISTINCT) से confuse करना
- bad joins hide करने के लिए DISTINCT इस्तेमाल करना
- यह भूल जाना कि 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: