如何检查SQL中的特定字段是否具有值

时间:2017-05-05 13:48:40

标签: sql-server

我有一个如下表,如果Date为null,那么我想得到WorkType

enter image description here

Empid Role WorkType1 DATE1     WorkType2 DATE2     WorkType3 DATE3
8     P001 Work1     NULL      Work2     NULL      Work3     NULL   
9     P002 Work2     12/9/2016 Work6     NULL      Work3     NULL
2     P003 Work3     NULL      Work6     12/9/2016 Work2     2/9/2016
7     P004 Work4     NULL      Work6     12/9/2016 Work5     NULL   
1     P005 Work5     12/9/2016 Work4     NULL      Work3     NULL
2     P006 Work6     NULL      Work1     12/9/2016 Work5     NULL

3 个答案:

答案 0 :(得分:1)

Easiet但不是最佳解决方案是简单地计算每列中的空值,然后您可以使用此子查询并计算总和。

fun_2(list(foo, bar, NULL))

答案 1 :(得分:0)

试试这个:

select count(*)-count(work1_date) as count_nulls_workdate1, 
       count(*)-count(work2_date) as count_nulls_workdate2,
       count(*)-count(work3_date) as count_nulls_workdate3 
      from Table;

count不计算空值,所以count(*)计算记录 - count(field)=空数

答案 2 :(得分:0)

下面的答案是我对你的要求的解释,你的问题有点不清楚。

SELECT
ID,
EMPLOYEE,
[ROLE],
WorkType1,
    CASE WHEN Date1 IS NULL THEN WorkType1 ELSE CAST(Date1 AS VARCHAR(23)) END Date1,
WorkType2,
    CASE WHEN Date2 IS NULL THEN WorkType2 ELSE CAST(Date2 AS VARCHAR(23)) END Date2,
WorkType3,
    CASE WHEN Date3 IS NULL THEN WorkType3 ELSE CAST(Date3 AS VARCHAR(23)) END Date3
WorkType4,
    CASE WHEN Date4 IS NULL THEN WorkType4 ELSE CAST(Date4 AS VARCHAR(23)) END Date4

当您将Worktype与Date值混合时,需要将Date显式转换为Varchar(23),而Date值是不兼容的数据类型我选择varchar(23)以允许datetime

根据您的数据库设置,您可能需要另外拆分日期以保留输出中所需的格式,下面给出了yyyy-MM-dd HH:mm:ss。

CAST(Datepart(Year,Date1) AS VARCHAR(4)) + '-'+ RIGHT('00'+CAST(Datepart(Month,Date1) AS VARCHAR(2)),2) + '-' + RIGHT('00' + CAST(Datepart(Day,Date1) AS VARCHAR(2)),2) + ' ' + RIGHT('00' + CAST(Datepart(HH,Date1) AS VARCHAR(2)),2)+ ':' + RIGHT('00'+CAST(Datepart(MINUTE,Date1) AS VARCHAR(2)),2) + ':' + RIGHT('00'+CAST(Datepart(ss,Date) AS VARCHAR(2)),2)

我使用以下方法测试

DECLARE @Date1 DATEtime = '2017-01-01', @Date2 DATEtime = NULL, @Date3 Datetime = '2017-01-02'
,@Worktype1 Varchar(20) = 'Test1'
,@Worktype2 Varchar(20) = 'Test2'
,@Worktype3 Varchar(20) = 'Test3'

SELECT
    CASE WHEN @Date1 IS NULL THEN @WorkType1 ELSE CAST(@Date1 AS VARCHAR(25)) END Date1, /*Varchar 23 date*/
    CASE WHEN @Date2 IS NULL THEN @WorkType2 ELSE CAST(@Date2 AS VARCHAR(25)) END Date2, /* Result of Worktype2 due to null */
    CASE WHEN @Date3 IS NULL THEN @WorkType3 ELSE CAST(Datepart(Year,@Date3) AS VARCHAR(4)) + '-'+ RIGHT('00'+CAST(Datepart(Month,@Date3) AS VARCHAR(2)),2) + '-' + RIGHT('00' + CAST(Datepart(Day,@Date3) AS VARCHAR(2)),2) + ' ' + RIGHT('00' + CAST(Datepart(HH,@Date3) AS VARCHAR(2)),2)+ ':' + RIGHT('00'+CAST(Datepart(MINUTE,@Date3) AS VARCHAR(2)),2) + ':' + RIGHT('00'+CAST(Datepart(ss,@Date3) AS VARCHAR(2)),2) END Date3 /* Result for Date 3 formatted to yyyy-MM-dd HH:mm:ss*/

提供以下结果集

[结果集] [1]:https://i.stack.imgur.com/Y1uUp.jpg