2011-06-21 159 views
2

我有一張表,其中包含一個id字段以及5個字段,每個星期一至星期五的每週一天,其中數據類型是位。SQL Where Where子句邏輯

表看起來像:

+---+--------+---------+-----------+----------+--------+ 
|id | Monday | Tuesday | Wednesday | Thursday | Friday | 
+---+--------+---------+-----------+----------+--------+ 
| 1 |  1 |  0 |   0 |  0 |  0 | 
+---+--------+---------+-----------+----------+--------+ 
| 2 |  1 |  0 |   0 |  0 |  0 | 
+---+--------+---------+-----------+----------+--------+ 
| 3 |  0 |  0 |   0 |  1 |  0 | 
+---+--------+---------+-----------+----------+--------+ 
| 4 |  1 |  0 |   0 |  0 |  1 | 
+---+--------+---------+-----------+----------+--------+ 

根據一天我想返回有位設置爲true的那一天行。我正在考慮用where子句做這件事,但不能讓它起作用。

我覺得我的邏輯有問題,非常感謝任何幫助!

DECLARE @tDay as INTEGER 
SET @tDay = datepart(weekday, getdate()) 

SELECT  id, monday, tuesday, wednesday, thursday, friday 
FROM   Days 
WHERE CASE WHEN @tDay = 2 then @tDay 
     Else Days.monday 
     End = 1 
     AND 
     CASE WHEN @tDay = 3 then @tDay 
     Else Days.tuesday 
     End = 1 
+0

你能展示一些你想要的樣本數據和樣本輸出嗎? – Kangkan

+0

1 True False True False True 2 True True True False如果是星期一,則爲true我只希望返回第一列的True爲true的行,謝謝! – sooty

+1

您可以直接編輯帖子。 – Kangkan

回答

3

如果SET DATEFIRST是7.你需要,如果你有一些其他的日期作爲一週的第一天調整這將工作。

DECLARE @tDay as INTEGER 
SET @tDay = datepart(weekday, getdate()) 

select id, monday, tuesday, wednesday, thursday, friday 
from Days 
where case @tDay 
     when 2 then monday 
     when 3 then tuesday 
     when 4 then wednesday 
     when 5 then thursday 
     when 6 then friday 
     end = 1 
2
SELECT  id, monday, tuesday, wednesday, thursday, friday 
FROM   Days 
WHERE 
     CASE @tDay 
      WHEN 2 THEN monday 
      WHEN 3 THEN tuesday 
      WHEN 4 THEN wednesday 
      WHEN 5 THEN thursday 
      WHEN 6 THEN friday 
      ELSE NULL 
     END = 1