我有一个名为timesheet的表。我有以下行
ID Status ProjId ActId Date
1 pending 1 1 2014-aug-07
2 denied 1 2 2014-aug-08
3 saved 1 3 2014-aug-09
4 approved 1 4 2014-aug-10
我使用了以下查询来获得所需的结果。
SELECT * from tblTimesheet
WHERE DATEPART(wk,spentDate) = 32 AND ((timesheetstatus = 'Pending' or timesheetstatus = 'Approved') and (timesheetstatus <> 'Saved' or timesheetstatus <> 'Denied'))
我对上述查询的预期结果是0.但是我得到的结果是1.
5 pending 1 1 2014-aug-11
6 pending 1 2 2014-aug-12
7 approved 1 3 2014-aug-13
8 approved 1 4 2014-aug-14
这种情况我的查询有效。
SELECT * from tblTimesheet
WHERE DATEPART(wk,spentDate) = 32 AND ((timesheetstatus = 'Pending' or timesheetstatus = 'Approved') and (timesheetstatus <> 'Saved' or timesheetstatus <> 'Denied'))
我对上述查询的预期结果是1.I得到的结果是1。
如何在mssql中编写上述要求的查询。 场景1已经完成。但是场景2没有工作。 如何实现预期的结果。 任何帮助将不胜感激!!!
答案 0 :(得分:1)
请注意,这是mysql的解决方案,因为它也被标记了。它使用MySQL的标准定义来度过一周的时间。 - 这似乎与您自己的定义不同。如果更符合您的定义,您可以使用WEEK(日期,3)或类似的东西。
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,Status VARCHAR(20) NOT NULL
,ProjId INT NOT NULL
,ActId INT NOT NULL
,Date DATE NOT NULL
);
INSERT INTO my_table VALUES
(1 ,'pending',1 ,1 ,'2014-08-07'),
(2 ,'denied', 1 ,2 ,'2014-08-08'),
(3 ,'saved', 1 ,3 ,'2014-08-09'),
(4 ,'approved', 1 ,4 ,'2014-08-10');
SELECT *,WEEK(date) FROM my_table;
+----+----------+--------+-------+------------+------------+
| ID | Status | ProjId | ActId | Date | WEEK(date) |
+----+----------+--------+-------+------------+------------+
| 1 | pending | 1 | 1 | 2014-08-07 | 31 |
| 2 | denied | 1 | 2 | 2014-08-08 | 31 |
| 3 | saved | 1 | 3 | 2014-08-09 | 31 |
| 4 | approved | 1 | 4 | 2014-08-10 | 32 |
+----+----------+--------+-------+------------+------------+
SELECT x.*
FROM my_table x
LEFT
JOIN my_table y
ON WEEK(y.date) = WEEK(x.date)
AND y.status NOT IN ('approved','pending')
WHERE y.id IS NULL;
+----+----------+--------+-------+------------+
| ID | Status | ProjId | ActId | Date |
+----+----------+--------+-------+------------+
| 4 | approved | 1 | 4 | 2014-08-10 |
+----+----------+--------+-------+------------+
编辑:结果与WEEK(日期,3)......
SELECT x.*
FROM my_table x
LEFT
JOIN my_table y
ON WEEK(y.date,3) = WEEK(x.date,3)
AND y.status NOT IN ('approved','pending')
WHERE y.id IS NULL;
Empty set (0.00 sec)
答案 1 :(得分:0)
试试这个
SELECT *
FROM tblTimesheet
WHERE YEARWEEK(STR_TO_DATE(Date,"%Y-%M-%d"))=YEARWEEK(CURDATE()) AND (status='pending' or status='approved');
答案 2 :(得分:0)
试试这个,
Select * from
(
SELECT * from tblTimesheet
WHERE DATEPART(wk,spentDate) = 32
AND (timesheetstatus = 'Pending' or timesheetstatus = 'Approved')
)tbl
where
(timesheetstatus <> 'Saved' or timesheetstatus <> 'Denied'