在SQL Server中需要有关DATE查询的帮助?

时间:2016-01-24 06:41:02

标签: sql sql-server

我在SQL Server中有两个表:

  1. EMP
  2. On_Vacation与列EmpId, LeaveType, StartingFrom, EndingTo,RejoiningDate
  3. On_Vacation表存储休假员工的信息。

    enter image description here

    我试图以这样的方式查询表格,即我的查询包含以下列:

    EmpId, 24-1-2016, 25-1-2016, 26-1-2016, 27-1-2016, 28-1-2016
    

    结果查询列是本周的日期。如果Employee未在这些日期休假,则应写入available。否则应该写保留类型。

    我对这类查询非常陌生,请帮助我专家..

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合执行此操作:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="JS/jquery-1.11.3.min.js"></script>
    <script src="JS/jquery.mmenu.all.min.js"></script>
    <link href="CSS/jquery.mmenu.all.css" rel="stylesheet" />
</head>
<body>
    <div>
        <a href="#myMenu">Open the menu</a>
        <nav id="myMenu">
            <ul>
                <li><a href="#">Sign up</a></li>
                <li>
                    <a href="#">Enter</a>
                    <ul class="vertical">
                        <li><a href="#">Log in</a></li>
                        <li><a href="#">Continue as guest</a></li>
                    </ul>
                </li>
            </ul>
        </nav>
   </div>

    <script type="text/javascript">
    $(document).ready(function () {
        $("#my-menu").mmenu({
            // Options
        });

    });
    </script>
</body>
</html>

答案 1 :(得分:1)

您无法在没有动态SQL的情况下更改列名(这会使问题复杂化)。 以下是另一个建议:您将日期表更改为包含星期几的名称,如下所示:

CREATE TABLE DaysWeeks 
  (CalYear SMALLINT NOT NULL,
   WeekNumber TINYINT NOT NULL,
   CalDate DATE NOT NULL,
   DayOfWeekNumber TINYINT,
   DayOfWeekName VARCHAR(9)
   CONSTRAINT PK_DaysWeeks PRIMARY KEY CLUSTERED (CalYear, WeekNumber, CalDate)
   )

的值如下:

INSERT INTO dbo.DaysWeeks
        ( CalYear, WeekNumber, CalDate,DayOfWeekNumber,DayOfWeekName )
VALUES  ( 2016, 4, '01/24/2016',1,'Sunday'),
        ( 2016, 4, '01/25/2016',2,'Monday'),
        ( 2016, 4, '01/26/2016',3,'Tuesday'),
        ( 2016, 4, '01/27/2016',4,'Wednesday'),
        ( 2016, 4, '01/28/2016',5,'Thursday'),
        ( 2016, 4, '01/29/2016',6,'Friday'),
        ( 2016, 4, '01/30/2016',7,'Saturday')

现在,您可以根据星期几来查询:

WITH cte AS (
SELECT EmpDays.Employee, EmpDays.CalDate, EmpDays.DoWName, ISNULL(v.Leave_Type,'Available') AS Available
FROM dbo.On_Vacation v
RIGHT OUTER JOIN
 (SELECT e.EmpID AS Employee, dw.CalDate AS CalDate, dw.DayOfWeekName AS DoWName
  FROM dbo.DaysWeeks dw,
      dbo.Employee e
      WHERE dw.CalYear = 2016 AND dw.WeekNumber = 4) AS EmpDays
ON
   v.EmpID = EmpDays.Employee
   AND v.StartingFrom <= empdays.CalDate 
   AND v.EndingTo >= empdays.CalDate
)
SELECT * FROM cte 
PIVOT (MAX(cte.Available) FOR DoWName IN (['Sunday'],['Monday'],['Tuesday'],['Wednesday'],['Thursday'],['Friday'],['Saturday'])

如果你真的需要列中的实际日期,我会调整它以使用动态SQL。但在这之前(恕我直言,使代码更难以阅读和维护,而不是这么简单),我问你将如何呈现数据,因此是否可以在报告或表示层。