合并两个sql查询select和count

时间:2015-05-26 08:17:43

标签: sql

您好我有两个SQL查询,我想合并或组合它们

查询1:

Select TableA.Name, TableB.Date
from TableA, TableB
where ID = ID_used;

QUERY2:

SELECT count(Date)
FROM  (SELECT DISTINCT Date
       FROM TableA, TableB
       group by Date;

我试过了:

  Select TableA.Name, TableB.Date
  from TableA, TableB
  where ID=ID_used inner join (SELECT count(Date)
                               FROM (SELECT DISTINCT Date
                                     FROM TableA, TableB
                                     group by Date)

但是它在联合查询中给出了语法错误。

我需要的结果:姓名,计数结果。

任何想法?

测试数据:

    TableA
    ---------------------
    Name            ID
    ---------------------
    John           1001
    Peter          1002

    TableB
    -----------------------
    Date            ID_used
    -----------------------
    2015.05.01.AM   1001
    2015.05.01.AM   1001
    2015.05.01.AM   1002
    2015.05.01.PM   1001
    2015.05.01.PM   1001
    2015.05.01.PM   1002
    2015.05.01.PM   1002
    2015.05.02.PM   1002

结果必须是:

    John       2
    Peter      3

3 个答案:

答案 0 :(得分:1)

据我所知,你需要的是这样的: (虽然我不确定,因为你没有添加测试数据和预期结果)

选择t1.Name,t2.Date,            (选择计数(日期)             从(选择不同的日期                   从TableA,TableB                   GROUP BY Date))as datecount     来自TableA t1     加入TableB t2     在t1.ID = t2.ID_used

更新:我认为这正是您所寻找的:SQLFIDDLE

public class AnyClass{

    public AnyClass(String jsonString){
        GSONObject gobject = new GSONObject(jsonString);
        String title = gobject.getValueOf("title");
    }
}

编辑:我在ms access 2010中试过这个:

注意:我无法使用关键字Date作为列名,因此更改为mydate

select t1.id, t1.name, count(t2.Date)
FROM TableA t1
JOIN (
SELECT Distinct id_used,Date
FROM TableB) t2
ON t1.id = t2.id_used
GROUP by t1.id

虽然有效,但我不建议在没有连接或关键字的情况下使用连接,所以这里有一个更好的可读性并且也可以工作:

select t1.id, t1.name, count(t2.mydate) as datecount
FROM TableA t1,
 (SELECT Distinct id_used,mydate
FROM TableB) t2
WHERE  t1.id = t2.id_used
GROUP by t1.id,t1.name

答案 1 :(得分:0)

这将返回tableA中每个Name的tableB的不同日期计数:

Select a.Name, COUNT(DISTINCT b.Date)
from TableA AS a JOIN TableB AS b
ON ID=ID_used
group by a.Name

答案 2 :(得分:-1)

在列名

之前使用tablename
Select TableA.Name,TableB.Date from TableA, TableB where ID=ID_used;