union 3表然后我想将空值显示为'X'

时间:2017-03-25 04:21:40

标签: sql database sql-server-2008 isnull

我有3个联合表,这是sql代码

SELECT * FROM
(SELECT DISTINCT userid, status , DATEPART(dd, [date]) as Date
FROM edrsDB..tbl_status
WHERE DATEPART(MM, [date]) = 3
And DATEPART(YYYY, [date]) = 2017
Union 
SELECT DISTINCT userid, status , DATEPART(DD,[date]) as Date
FROM edrsDB..tbl_public_holiday
WHERE DATEPART(MM, [date]) = 3
And DATEPART(YYYY, [date]) = 2017
Union
SELECT DISTINCT userid, status , DATEPART(DD,[Date]) as Date 
FROM edrsDB..tbl_station_weekend
WHERE DATEPART(MM, [date]) = 3
And DATEPART(YYYY, [date]) = 2017
And date IS NOT NULL) AS monthlyRpt
PIVOT (MAX(status)
FOR userid IN (XSP, BSR, BPT, XPW, IPH, XTH, TGG, XKG, XKM, XLG, KBR, KUA, LGK,MKZ, PEN, XGM, JHB, XBN, STW, TIN, MUA)) AS pivottable

运行此sql查询后我得到了很多空...所以我希望空值显示为'X'

任何人都可以提出建议吗

这是结果

null result after union

1 个答案:

答案 0 :(得分:0)

请尝试

select
    Date,
    isnull(XSP, 'X') as XSP,
    isnull(BSR, 'X') as BSR,
    isnull(BPT, 'X') as BPT,
    isnull(XPW, 'X') as XPW,
    isnull(IPH, 'X') as IPH,
    isnull(XTH, 'X') as XTH,
    isnull(TGG, 'X') as TGG,
    isnull(XKG, 'X') as XKG,
    isnull(XKM, 'X') as XKM,
    isnull(XLG, 'X') as XLG,
    isnull(KBR, 'X') as KBR,
    isnull(KUA, 'X') as KUA,
    isnull(LGK, 'X') as LGK,
    isnull(MKZ, 'X') as MKZ,
    isnull(PEN, 'X') as PEN,
    isnull(XGM, 'X') as XGM,
    isnull(JHB, 'X') as JHB,
    isnull(XBN, 'X') as XBN,
    isnull(STW, 'X') as STW,
    isnull(TIN, 'X') as TIN,
    isnull(MUA, 'X') as MUA
FROM
(
    SELECT DISTINCT userid, status , DATEPART(dd, [date]) as Date
    FROM edrsDB..tbl_status
    WHERE DATEPART(MM, [date]) = 3
    And DATEPART(YYYY, [date]) = 2017
    Union 
    SELECT DISTINCT userid, status , DATEPART(DD,[date]) as Date
    FROM edrsDB..tbl_public_holiday
    WHERE DATEPART(MM, [date]) = 3
    And DATEPART(YYYY, [date]) = 2017
    Union
    SELECT DISTINCT userid, status , DATEPART(DD,[Date]) as Date 
    FROM edrsDB..tbl_station_weekend
    WHERE DATEPART(MM, [date]) = 3
    And DATEPART(YYYY, [date]) = 2017
    And date IS NOT NULL
) AS monthlyRpt
PIVOT (MAX(status)
    FOR userid IN (XSP, BSR, BPT, XPW, IPH, XTH, TGG, XKG, XKM, XLG, KBR, KUA, LGK,MKZ, PEN, XGM, JHB, XBN, STW, TIN, MUA)
) AS pivottable