我试图将一年中明智的叶子分配给我的数据库(sql server),但它失败了。下面是我试过的代码

时间:2016-11-04 13:47:58

标签: sql-server

我试图在我的数据库(sql server)中分配一年中明智的叶子,但它在我的尝试代码下面失败了

select count(*)(SELECT DATEPART(yyyy,Date) AS OrderYear,
DATEPART(mm,Date) AS OrderMonth,
DATEPART(dd,Date) AS OrderDay
FROM Leaves
WHERE EmployeeID=37) FROM Leaves where OrderYear = '2016'

2 个答案:

答案 0 :(得分:0)

以下代码将执行您需要执行的操作。只需对上面的代码做一些小改动:

  1. 您将需要一个内部查询,它将提取日期部分,然后需要选择它们。
  2. 外部查询需要从内部查询中选择并过滤新的日期部分字段。
  3. 我将如何做到这一点:

    select 
        count(*)
    FROM
    (
        SELECT 
            DATEPART(yyyy, Date) AS OrderYear,
            DATEPART(mm, Date) AS OrderMonth,
            DATEPART(dd, Date) AS OrderDay
        FROM 
            Leaves
        WHERE 
            EmployeeID = 37
    ) A
    WHERE 
        OrderYear = '2016';
    

答案 1 :(得分:0)

您可以寻找:

;WITH CTE AS(

 SELECT 1 as MonthNumber 
 UNION ALL
 SELECT MonthNumber+1 AS MonthNumber
 FROM CTE
 WHERE MonthNumber<=12
)
SELECT MonthNumber,COUNT(*) 
FROM CTE
LEFT JOIN Leaves ON MONTH(DATE) = MonthNumber AND EmployeeID=37 AND YEAR(Date)=2016 
GROUP BY MonthNumber