0

如何组合以下 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
4

2 回答 2

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
于 2013-04-18T15:46:50.190 回答
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 来获取上个月的日期?

于 2013-04-18T16:03:33.270 回答