现有俩个表:
表一:包含ID列,和V1、V2、V3三个列
ID V1 V2 V3
------------------------
00001 2 -1 3
00002 3 4 4
00003 4 1 27
表二:表中Col列中的V1、V2、V3三个列对应表一中的三个列。Min和Max分别限定V1、V2、V3的极大值和极小值。
Col Min MAX
------------------------
V1 -2 1
V2 2 4
V3 1 15
请问大家通过什么SQL语句,查询出表一中不合格的行和字段名?
如果不好写SQL语句的话,不用数据库,怎么高效地实现?
SQL 极值判断 性能
------解决方案--------------------
--> 测试数据:@T
declare @T table([ID] varchar(5),[V1] int,[V2] int,[V3] int)
insert @T
select '00001',2,-1,3 union all
select '00002',3,4,4 union all
select '00003',4,1,27
select 'V1' as Col,min(v1) as [min],MAX(v1) as [max] from @T
union all
select 'V2',min(v2),MAX(v2) from @T
union all
select 'V3',min(v3),MAX(v3) from @T
/*
Col min max
---- ----------- -----------
V1 2 4
V2 -1 4
V3 3 27
*/
------解决方案--------------------
DECLARE @a TABLE(ID CHAR(5), V1 INT,V2 INT, V3 INT)
INSERT @a SELECT '00001', 2, -1, 3
union all select '00002', 3, 4, 4
union all select '00003', 4, 1, 27
DECLARE @b TABLE(Col VARCHAR(20),[Min] INT, [MAX] INT)
INSERT @b SELECT 'V1', -2, 1
UNION ALL SELECT 'V2', 2 , 4
UNION ALL SELECT 'V3', 1 , 15