SQL Server:在CASE表达式后排除具有NULL值的行

时间:2015-09-29 19:46:44

标签: sql-server max case min

下面的查询以我想要的方式聚合来自日志记录表的数据......

SELECT 
    [TransactionNumber]
    ,MIN(CASE WHEN [Entry] = 'Updated status to Awaiting OCLC Sending' THEN [DateTime] END) AS 'start' 
    ,MAX(CASE WHEN [Entry] = 'Updated Status to: Delivered to Web' THEN [DateTime] END) AS 'end' 
    FROM [ILLData].[dbo].[History]
    GROUP BY [TransactionNumber] 
    /*
    227882  2015-09-29 14:17:07.443 2015-09-29 15:27:03.180
    227883  NULL    NULL
    227884  2015-09-29 14:29:22.340 NULL
    227885  NULL    2015-09-29 14:59:54.677
    */

...但我想排除任何包含NULL值的结果行。我尝试了下面的查询,但我一直得到相同的结果,并且不排除具有NULL值的行。

SELECT 
    [TransactionNumber]
    ,MIN(CASE WHEN [Entry] = 'Updated status to Awaiting OCLC Sending' THEN [DateTime] END) AS 'start' 
    ,MAX(CASE WHEN [Entry] = 'Updated Status to: Delivered to Web' THEN [DateTime] END) AS 'end' 
FROM 
    [ILLData].[dbo].[History]
WHERE 
    'start' IS NOT NULL 
    AND 'end' IS NOT NULL 
GROUP BY 
    [TransactionNumber] 

/* still get rows with NULL values */

SELECT 
    [TransactionNumber]
    ,MIN(CASE WHEN [Entry] = 'Updated status to Awaiting OCLC Sending' THEN [DateTime] END) AS 'start' 
    ,MAX(CASE WHEN [Entry] = 'Updated Status to: Delivered to Web' THEN  [DateTime] END) AS 'end' 
FROM 
    [ILLData].[dbo].[History] 
GROUP BY  
    [TransactionNumber] 
HAVING 
    'start' IS NOT NULL 
    AND 'end' IS NOT NULL

/* still get rows with NULL values */

WITH history AS 
(
   SELECT  
       [TransactionNumber]
       ,MIN(CASE WHEN [Entry] = 'Updated status to Awaiting OCLC Sending' THEN [DateTime] END) AS 'start' 
       ,MAX(CASE WHEN [Entry] = 'Updated Status to: Delivered to Web' THEN [DateTime] END) AS 'end' 
   FROM 
       [ILLData].[dbo].[History]
   GROUP BY 
       [TransactionNumber])
SELECT * 
FROM history 
WHERE 'start' IS NOT NULL 
  AND 'end' IS NOT NULL 

/* still get rows with NULL values */

有没有办法过滤使用CASE的查询结果?

1 个答案:

答案 0 :(得分:0)

问题在于您的字段名称,因为'start'永远不会为null,因为SQL将文本值与null进行比较。几乎没有变化,你的查询也没问题。

# here we take access token from session, assuming you already got it
# sometime before and stored it there for future use
client = Instagram.client(:access_token => session[:access_token])
photos = client.user_recent_media