日期:2014-05-18  浏览次数:20746 次

请教一条SQL语句的写法(在线)
数据如下:
A B C
===========================
1 1 2007-1-21
2 1 2007-1-22
3 0 2007-1-1
4 0 2007-1-2
5 1 2007-1-23
6 0 2007-1-3
7 0 2007-1-23
8 0 2007-1-25
9 1 2007-1-24
============================
要显示出所有B=0数据,但排除在B=1的情况下,C在2007-1-22到2007-1-23之外的数据。

查询后的结果集应该如下:
A B C
===========================
2 1 2007-1-22
3 0 2007-1-1
4 0 2007-1-2
5 1 2007-1-23
6 0 2007-1-3
7 0 2007-1-23
8 0 2007-1-25
============================

想了半天,不知道怎么做,谢谢各位了!

------解决方案--------------------
SQL code
CREATE TABLE tb (a varchar(2),b varchar(2),c datetime)
INSERT INTO tb VALUES ('1','1','2007-1-21')
INSERT INTO tb VALUES ('2','1','2007-1-22')
INSERT INTO tb VALUES ('3','0','2007-1-1')
INSERT INTO tb VALUES ('4','0','2007-1-2')
INSERT INTO tb VALUES ('5','1','2007-1-23')
INSERT INTO tb VALUES ('6','0','2007-1-3')
INSERT INTO tb VALUES ('7','0','2007-1-23')
INSERT INTO tb VALUES ('8','0','2007-1-25')
INSERT INTO tb VALUES ('9','1','2007-1-24')

SELECT * FROM TB WHERE (B='0') OR NOT (B='1' AND C NOT BETWEEN '2007-1-22' AND '2007-1-23')

DROP TABLE TB

------解决方案--------------------
CREATE TABLE tb (a varchar(2),b varchar(2),c datetime)
INSERT INTO tb VALUES ('1','1','2007-1-21')
INSERT INTO tb VALUES ('2','1','2007-1-22')
INSERT INTO tb VALUES ('3','0','2007-1-1')
INSERT INTO tb VALUES ('4','0','2007-1-2')
INSERT INTO tb VALUES ('5','1','2007-1-23')
INSERT INTO tb VALUES ('6','0','2007-1-3')
INSERT INTO tb VALUES ('7','0','2007-1-23')
INSERT INTO tb VALUES ('8','0','2007-1-25')
INSERT INTO tb VALUES ('9','1','2007-1-24')

select * from tb where b=0 or b=1 and c between '2007-1-22' and '2007-1-23'
------解决方案--------------------
SQL code
SELECT * FROM TB WHERE (B='0') OR (B='1' AND C BETWEEN '2007-1-22' AND '2007-1-23')

------解决方案--------------------
SQL code
--> 测试数据: #T
if object_id('tempdb.dbo.#T') is not null drop table #T
create table #T (A int,B int,C datetime)
insert into #T
select 1,1,'2007-1-21' union all
select 2,1,'2007-1-22' union all
select 3,0,'2007-1-1' union all
select 4,0,'2007-1-2' union all
select 5,1,'2007-1-23' union all
select 6,0,'2007-1-3' union all
select 7,0,'2007-1-23' union all
select 8,0,'2007-1-25' union all
select 9,1,'2007-1-24'

select * from #T where B=0 or (B=1 and c between '2007-1-22' and '2007-1-23')
/*
A           B           C
----------- ----------- -----------------------
2           1           2007-01-22 00:00:00.000
3           0           2007-01-01 00:00:00.000
4           0           2007-01-02 00:00:00.000
5           1           2007-01-23 00:00:00.000
6           0           2007-01-03 00:00:00.000
7           0           2007-01-23 00:00:00.000
8           0           2007-01-25 00:00:00.000
*/

------解决方案--------------------
要显示出所有B=0数据,但排除在B=1的情况下,C在2007-1-22到2007-1-23之外的数据。
----------------------------
(所有B=0的数据) 或者 (B=1并且C在2007-1-22到2007-1-23之间的数据)
没难度,楼主没理清逻辑而已。