我有一个SQLite表,其中有一个消息列表:
to | from
==========
9999 ME
9999 ME
ME 9999
ME 8888
查询结果应采用以下格式:
数字(匹配的记录数)
9999 (3)
8888 (1)
如何编写查询以向我提供此结果集?我正在使用Android。
答案 0 :(得分:2)
也许您可以使用此http://www.postgresql.org/docs/current/static/functions-conditional.html
执行某些操作我想这样的事情(没有运行它):
SELECT number, count(number) as `Count` FROM (
SELECT
CASE
WHEN to = 'ME' THEN from
ELSE to
END AS number
FROM table
) GROUP BY number;
答案 1 :(得分:2)
SELECT value, count(*)
FROM (
SELECT to as value
FROM your_table
UNION ALL
SELECT "from" as value
FROM your_table
) t
GROUP BY value
要过滤掉to
和from
的不需要的值,请使用适当的WHERE子句(理想情况是在内部选择中,以减少需要处理的行数。
答案 2 :(得分:1)
select value, sum (count) as count, from
(
select count(*) as count , "from" as value from your_table
group by "from"
union all
select count(*) as count , "to" as value from your_table
group by "to"
) t
group by t.value
谢谢@a_horse_with_no_name& @razvi!
答案 3 :(得分:0)
如果您只想计算数值的出现次数,这应该有用。
使用连接(“||”)来形成所需的输出。
SELECT to_from || ' (' || count(to_from) || ')' FROM (
SELECT
CASE
WHEN to ~ '^[0-9]+$' THEN to
WHEN from ~ '^[0-9]+$' THEN from
END to_from
FROM
testing
) a
GROUP BY to_from
结果
?column?
----------
9999 (3)
8888 (1)
(2 rows)