两个带有一个公共列的子查询

时间:2016-01-21 09:28:15

标签: sql select sql-server-2012

我将原始问题更改为更具体。

运行此查询后,我想要输出两个参数。 这两个参数需要不同的标准。

为此,我建立了这种查询:

SELECT m.count, ytd.count 
FROM ( 
   SELECT COUNT( id ) count 
   FROM table 
   WHERE date BETWEEN BETWEEN '2010-06-01' AND '2010-06-30'
) m, (SELECT COUNT( id )count 
      FROM table 
      WHERE date BETWEEN BETWEEN '2010-01-01' AND '2010-06-30'
) ytd 

这种查询返回计数并且运行良好。 但是现在我想再挖一点,然后通过dep来看这两个参数。

现在我得到了总数:

Param1  Param2
  39      85

我希望得到这张表:

Dep Param1 Param2
  1    5      7
  2    34     78

依旧......

希望现在更清楚。

谢谢!

1 个答案:

答案 0 :(得分:0)

    SELECT m.dep, m.count, ytd.count 
    FROM ( 
          SELECT COUNT( id ) count, Dep 
          FROM table 
          WHERE date BETWEEN BETWEEN '2010-06-01' AND '2010-06-30'
          group by dep
    ) m, 

Join

(   SELECT COUNT( id )count, dep 
          FROM table 
          WHERE date BETWEEN BETWEEN '2010-01-01' AND '2010-06-30'
          group by dep
    ) ytd

ON ytb.dep=m.dep

感谢您的帮助