没有获得UNION的SQL查询以返回正确的值

时间:2014-07-17 18:04:12

标签: sql sqlite count union

带有UNION查询的ISSUES,从一个表中,我需要“Term”的COUNT个记录,其中我指定了“ID”和“Count”字段。

注意如果怀疑使用了UNION ALL,评分者会降级。

我正在尝试一些不同的格式......但没有一种格式正常。

------(版本1)-------

e.g。

    select count(term) from frequency where (select docid =
    '10398_txt_earn' where count = '1' UNION select docid =
    '925_txt_trade' where count = '1');

给我“0”平地机告诉我“0”不正确。

如果我分成两部分,我会得到一个值(110和225)。

------(版本2)-------

我使用以下格式修改了查询:

http://sqlite.1065341.n5.nabble.com/UNION-QUERY-td42629.html

所以我现在有查询(BTW ...不像海报建议的那样,我必须使用UNION ...除非我可以使用UNION ALL然后选择唯一的记录......但这似乎是一个不必要的计算步骤)

   select count(term) from (select * from frequency where
   (docid='10398_txt_earn' and count='1'))
   UNION
   select term from (select * from frequency where 
   (docid='925_txt_trade' and count='1'));

给了我两行输出:第1行:110,第2行:225

如果我将'select count(term)'替换为'select term'...我得到一个列表,其长度是上面两个值的总和

------(版本3)-------

  select (term) from frequency where (select docid = '10398_txt_earn' 
  where count = '1')
  UNION
  select (term) from frequency where (select docid = '925_txt_trade' 
  where count = '1');

再次,给我两行输出:第1行:110行,第2行:225

问题??? 你将如何修改它,以便获得一个具有UNIQUE共享条件数的值?

3 个答案:

答案 0 :(得分:1)

我会用这个

select count(term) from frequency where docid in ('10398_txt_earn' '925_txt_trade') AND count = '1';

但是如果你需要使用UNION

select sum(termCount) from (
select count(term) termCount from (select * from frequency where
docid='10398_txt_earn' and count='1' group by term)
 UNION
select count(term) from (select * from frequency where 
docid='925_txt_trade' and count='1' group by term)
);

答案 1 :(得分:1)

你正在寻找两个项目的计数(一个where子句),还需要它也是“count”='1'的位置?这对我来说很直接 - 一个where where子句。

SELECT SUM(TermCounts)
FROM (
    SELECT COUNT(DISTINCT terms) AS TermCounts
    FROM frequency
    WHERE docid = '10398_txt_earn'
        AND "count" = '1'
    UNION ALL
    SELECT COUNT(DISTINCT terms) AS TermCounts
    FROM frequency
    WHERE docid = '925_txt_trade'
) CountUnion;

答案 2 :(得分:0)

得到它......这有效:

from (
select term
from frequency
where docid in ("10398_txt_earn") AND count = '1'
UNION
select term
from frequency
where docid in ("925_txt_trade") AND count = '1');