group_concat only when more than one to group
I'd like to pe开发者_如何学JAVArform a group-concat in SQLite only on those records where there is more than one row to concatenate. It seems like you could do this beforehand (count records using a group by then remove those singleton rows before proceeding with the group_concat); after (complete the group_concat then remove rows where nothing was concatenated); or possibly even during?
My question: what's the fastest way for SQLite to accomplish this?
I've worked out an "after" example using APSW in Python, but am not happy with it:
#set up a table with data
c.execute("create table foo(x,y)")
def getvals():
a = [1, 1, 2, 3, 3]
b = ['a','b','c','d','e']
for i in range(5):
yield a[i],b[i]
c.executemany("insert into foo values(?,?)",getvals())
c.execute('''create table fooc(a,b);
insert into fooc(a,b) select x, group_concat(y) from foo group by x''')
c.execute('select * from fooc')
c.fetchall() ## reports three records
c.execute("select * from fooc where b like '%,%'")
c.fetchall() ## reports two records .. what I want
It seems crazy (and slow?) to use LIKE for this kind of need.
Add a HAVING
clause to your query:
INSERT INTO fooc(a,b)
SELECT x, group_concat(y)
FROM foo
GROUP BY x
HAVING COUNT(*) > 1
精彩评论