Get more than 2 columns distinct data using group by in postgresql

时间:2015-10-06 08:24:01

标签: postgresql group-by

CREATE TABLE "spiral_articleinfo" (
    "id" integer NOT NULL PRIMARY KEY,
    "url" varchar(255) NOT NULL UNIQUE,
    "articletitle" varchar(1000) NOT NULL,
    "articleimage" text,
    "articlecontent" text NOT NULL,
    "articlehtml" text NOT NULL,
    "articledate" date,
    "articlecategory" varchar(1000) NOT NULL,
    "s_articlecategory" varchar(1000),
    "articlesubcategory" varchar(1000) NOT NULL,
    "articledomain" varchar(255),
    "domainrank" integer NOT NULL,
    "articletags" text NOT NULL,
    "articleprice" decimal NOT NULL,
    "contenthash" varchar(255) UNIQUE
);

This is the table schema. I want to get distinct articlecategory for every article present group by articledomain. I did:

select distinct articledomain, articlecategory 
from spiral_articleinfo       
group by articledomain 
order by articledomain;

Error coming is:

ERROR: column "spiral_articleinfo.articlecategory" must appear in the GROUP BY clause or be used in an aggregate function.

How do I get articlecategories?

When I run this query:

select distinct articledomain, articlecategory, articlesubcategory
from spiral_articleinfo;

I get:

articledomain      | articlecategory | articlesucategory
 androidadvices.com|    Android Apps | Books & Reference
 androidadvices.com|    Android Apps | Business

I want the result to be one domain following its articlecategory and articlesubcategory fields. Sample Output:

articledomain        | articlecategory | articlesucategory
 androidadvices.com  |    Android Apps | Books & Reference, Business
 www.womensweb.in    |             Home|Social Lens, Crime, Law, Safety
 suitcaseofstories.in|         Himachal|Ladakh, People, Street Photography

1 个答案:

答案 0 :(得分:1)

您可以使用string_agg()功能和GROUP BY来实现所需的输出:

以下为例:

create table foow (articledomain text,articlecategory text,articlesucategory text);

insert into foow values ('androidadvices.com','Android Apps','Books & Reference');
insert into foow values ('androidadvices.com','Android Apps','Business');

并且select语句应该是

 select articledomain
       ,articlecategory
       ,string_agg(articlesucategory,',') 
 from foow 
 group by articledomain, articlecategory

SQLFIDDLE DEMO