我有一个错误的表结构。我尝试尽可能少地修改它,因为真正的问题更复杂。我在SQL Server 2005中工作。
这是我的表:
tbl_item
export PGPASSWORD=dbpass
psql --dbname=dbpass --username=dbuser --host=127.0.0.1 -c "COPY (SELECT * FROM widget) TO stdout DELIMITER ',' CSV HEADER" > export.csv
查询:
id | item
---+------
1 | car
2 | car
3 | car, => This is what I focus
4 | jet
5 | jet, car => This is just an example of the comma purpose
结果:
SELECT item, count(*) AS sum
FROM tbl_item
GROUP BY item
ORDER BY sum DESC
我想要的是这样的:
item | sum
--------+-------
car | 2
car, | 1
jet | 1
jet,car | 1
我试过了:
item | sum
---------+--------
car | 3
jet | 1
jet, car | 1 => actually I don't care about this, but this just for example
但结果是:
SELECT REPLACE(item,',',''), count(*) AS sum
FROM tbl_item
GROUP BY item
ORDER BY sum DESC
我可以用PHP操作这么简单,但我想知道如何使用纯SQL Server。
提前致谢!
答案 0 :(得分:3)
尝试:
GROUP BY REPLACE(item,',','')
这将规范化项目,然后分组。
答案 1 :(得分:3)
您需要将其添加到group by子句中:
SELECT REPLACE(item,',',''), count(*) AS sum
FROM tbl_item
GROUP BY replace(item,',','')
ORDER BY sum DESC