日期:2014-05-19  浏览次数:20439 次

一个奇怪的查询问题
CREATE   TABLE   [dbo].[A]   (
[Type]   [varchar]   (10)   COLLATE   Chinese_PRC_CI_AI   NULL   ,
[id]   [int]   NULL   ,
[name]   [varchar]   (10)   COLLATE   Chinese_PRC_CI_AI   NULL  
)   ON   [PRIMARY]
GO


INSERT   A
SELECT   'A ',4, 'Z '   UNION   ALL
SELECT   'A ',5, 'X '   UNION   ALL
SELECT   'B ',4, 'Q '   UNION   ALL
SELECT   'B ',5, 'W '   UNION   ALL
SELECT   'C ',4, 'Y '   UNION   ALL
SELECT   'D ',4, 'U '  

SELECT   TYPE,NAME=MAX(ISNULL(CASE   WHEN   ID= '4 '   THEN   NAME   END,CASE   WHEN   ID= '5 'THEN   NAME   END))
FROM   A  
GROUP   BY   TYPE
ORDER   BY   TYPE

上面的语句为什么得到的不是下面的结果?

--------------------
TYPE         NAME
A Z
B Q
C Y
D U

------解决方案--------------------
因为 W > Q
------解决方案--------------------
规则是什么
------解决方案--------------------
我们来看B这一组
'B ',4, 'Q ' 对应的isnull(……) = Q
'B ',5, 'W ' 对应的isnull(……) = W

然后再max,当然就是W了

------解决方案--------------------
declare @A TABLE(
[Type] [varchar] (10) COLLATE Chinese_PRC_CI_AI NULL ,
[id] [int] NULL ,
[name] [varchar] (10) COLLATE Chinese_PRC_CI_AI NULL
)


INSERT @A
SELECT 'A ',4, 'Z ' UNION ALL
SELECT 'A ',5, 'X ' UNION ALL
SELECT 'B ',4, 'Q ' UNION ALL
SELECT 'B ',5, 'W ' UNION ALL
SELECT 'C ',4, 'Y ' UNION ALL
SELECT 'D ',4, 'U '

SELECT TYPE,NAME=MAX(NAME)
FROM @A
GROUP BY TYPE
ORDER BY TYPE

--结果
TYPE NAME
---------- ----------
A Z
B W
C Y
D U

(所影响的行数为 4 行)

--搂主列出的结果是错的

------解决方案--------------------
估计楼主的要求是有4就选择4 没有4就选择5

declare @A TABLE(
[Type] [varchar] (10) COLLATE Chinese_PRC_CI_AI NULL ,
[id] [int] NULL ,
[name] [varchar] (10) COLLATE Chinese_PRC_CI_AI NULL
)


INSERT @A
SELECT 'A ',4, 'Z ' UNION ALL
SELECT 'A ',5, 'X ' UNION ALL
SELECT 'B ',4, 'Q ' UNION ALL
SELECT 'B ',5, 'W ' UNION ALL
SELECT 'C ',4, 'Y ' UNION ALL
SELECT 'D ',5, 'U '

SELECT TYPE,NAME
FROM @A a
where id=4 or (
id=5 and not exists (
select 1 from @A
where type=a.type
and id=4
)
)

--结果
--------------------
TYPE NAME
A Z
B Q
C Y
D U


------解决方案--------------------
SELECT TYPE,NAME=isnull(MAX(case id when 4 then name end),MAX(case id when 5 then name end))
FROM A
GROUP BY TYPE
ORDER BY TYPE