如何在sqlserver中组合这两个查询

时间:2013-04-18 15:38:39

标签: sql-server

如何组合以下2个sqlserver查询

select COUNT(dept) as totalDept
from 
employee
where DATEPART(MM,joindate) = DATEPART(MM, DATEADD(MM, -1, getdate()))
AND DATEPART(YYYY, joindate) = DATEPART(YYYY, DATEADD(MM, -1, getdate()))
group by (DATENAME(MONTH,joindate)+' , '+DATENAME(YEAR,joindate))

select COUNT(*) from employee
group by dept

2 个答案:

答案 0 :(得分:0)

试试这个 -

SELECT 
      totalDept = count(dept) 
    , gr.grouped_by_dept
FROM employee
CROSS JOIN (
    SELECT grouped_by_dept = count(1)
    FROM employee
    GROUP BY dept
) gr
WHERE datepart (MM, joindate) = datepart (MM, dateadd(MM, -1, getdate()))
    AND datepart (YYYY, joindate) = datepart (YYYY, dateadd(MM, -1, getdate()))
GROUP BY datename (MONTH, joindate) + ' , ' + datename (YEAR, joindate)

<强>更新

DECLARE @FirstDayOfMonth DATETIME
SELECT @FirstDayOfMonth = DATEADD(DAY, -(DAY(GETDATE()) - 1), GETDATE())

SELECT 
      t2.MONTHYEAR
    , t2.[system]
    , t3.[countBySystem]
    , NewAddr = COUNT(t2.[address])
FROM (
    SELECT 
          MONTHYEAR = DATENAME(MONTH, DateInserted) + ' , ' + DATENAME(YEAR, DateInserted)
        , t.[system]
        , t.[address]
    FROM dbo.testtable t
    WHERE DATEADD(DAY, -(DAY(t.DateInserted) - 1), t.DateInserted) = @FirstDayOfMonth
) t2
JOIN (
    SELECT 
          t2.[system]
        , [countBySystem] = COUNT(1)
    FROM dbo.testTable t2 
    GROUP BY t2.[system]
) t3 ON t2.[system] = t3.[system]
GROUP BY 
      t2.MONTHYEAR
    , t2.[system]
ORDER BY NewAddr

答案 1 :(得分:0)

我喜欢with子句:

WITH 
total_employees AS
    (select dept,count(*) as emp_count from employee group by dept),
recent_employees AS 
    (select dept,count(*) as new_emp_count from employee 
WHERE
    DATEPART(MM,joindate) = DATEPART(MM, DATEADD(MM, -1, getdate()))
AND 
    DATEPART(YYYY, joindate) = DATEPART(YYYY, DATEADD(MM, -1, getdate()))
SELECT 
    total_employees.dept,emp_count "Total",new_emp_count,"New" 
FROM 
    total_employees,recent_employees
WHERE
    total_employees.dept = recent_employees.dept

由于我没有测试过,可能会出现轻微的语法错误,但我的报告非常相似。

你有没有理由不使用datediff来获取上个月的日期?