有3个表a,b,c有共同的2个项ID,P,都不是主键1,希望查询各个ID在三个表内P值=2的总记录数
2,得出的结果如何分ID储存在表D里?
表D结构:
    ID  P
值  01  4
    02  3

解决方案 »

  1.   

    楼主解释下这句:希望查询各个ID在三个表内P值=2的总记录数
    实在不明白
      

  2.   

    1.
    select count(*) as Total from 
    (select count(ID) from a where p = 2
    union 
    select count(ID) from b where p = 2
    union 
    select count(ID) from c where p = 2)
    是这样吗?楼主
      

  3.   

    我意思是根据不同ID把三个表中p值等于2的记录数加起来
    比如a中
    ID P
    1  2
    2  1
    3  2b中
    ID  P
    1   1
    2   2
    3   1C中
    ID  P
    1   2
    2   2
    3   2
    要得出如下结果在D内
    ID  SUM
    1    2
    2    2
    3    1
      

  4.   

    select count(*) as Total ,XID from 
    (select count(ID) ,min(Id) as XID from a where p = 2
    union 
    select count(ID),min(Id) as XID  from b where p = 2
    union 
    select count(ID),min(Id) as XID  from c where p = 2)
    group XID可能不行,自己再改改,就是这个思路
      

  5.   

    select id,count(*) from 
    (
    select * from a
    union all
    select * from b
    union all
    select * from c
    )g where p=2 group by id
      

  6.   

    select id,count(*)sum into d from 
    (
    select * from a
    union all
    select * from b
    union all
    select * from c
    )g where p=2 group by id按照你上面的例子得出的结果应该是
    ID  SUM
    1    2
    2    2
    3    2
      

  7.   

    select id,count(*)sum into d from 
    (
    select * from a
    union all
    select * from b
    union all
    select * from c
    )g where p=2 group by id试了,很对
      

  8.   

    服务器: 消息 8157,级别 16,状态 1,行 2
    包含 UNION 运算符的查询表达式中的所有查询都必须在选择列表中包含同样数目的表达式。
      

  9.   

    select id,count(*)sum into d from 
    (
    select P from a
    union all
    select P from b
    union all
    select P from c
    ) where p=2 group by id
      

  10.   

    服务器: 消息 156,级别 15,状态 1,行 9
    在关键字 'where' 附近有语法错误。
      

  11.   

    回复人: flybox728() ( ) 信誉:99 的方法很对的啊,有什么问题呢?
      

  12.   

    服务器: 消息 8157,级别 16,状态 1,行 2
    包含 UNION 运算符的查询表达式中的所有查询都必须在选择列表中包含同样数目的表达式。
      

  13.   

    select id,count(*)sum into d from 
    (
    select id,p from a
    union all
    select id,p from b
    union all
    select id,p from c
    )g where p=2 group by id那就这样写咧,列出字段名
    g 是别名,随便你怎么写都行
    拜托,多动点脑筋行不行。
      

  14.   

    flybox728() 拜托!!我新学SQL,肯定多问题问的,要是都会了也不会在这问呀!!!