I have a SQL Server query that tries to choose NULL
if there is at least one NULL
in column PredComplDate
or the latest date stored as NVARCHAR(30)
The weird thing is that when I run the query it returns correct results, but when my co-worker runs the query on the same computer it returns different results.
I saved the table created when my co-worker ran the query under a different name and compared it to the one that was created when I run the query. everything is the same, number of records, data type etc, but the below part of the query does not return NULL
for some reason:
SELECT [Reference Number],
CASE
WHEN LEN(Predecessors)>0 AND MAX(COALESCE(PredComplDate,'31/12/2099'))='31/12/2099' THEN NULL
ELSE MAX(PredComplDate)
END AS LatestPredComplDate
FROM mytable33
GROUP BY [Reference Number],Predecessors
what is the problem with this query?
mytable33
has been created by me and mytable22
has been created by my co-worker. when I query the results are identical:
SELECT Predecessors,[Reference Number], PredRefNo,PredComplDate FROM mytable22
SELECT Predecessors,[Reference Number], PredRefNo,PredComplDate FROM mytable33
when I run the above-mentioned query on both tables, the result is different:
SELECT [Reference Number],
CASE
WHEN LEN(Predecessors)>0 AND MAX(COALESCE(PredComplDate,'31/12/2099'))='31/12/2099' THEN NULL
ELSE MAX(PredComplDate)
END AS LatestPredComplDate
FROM mytable22
GROUP BY [Reference Number],Predecessors
SELECT [Reference Number],
CASE
WHEN LEN(Predecessors)>0 AND MAX(COALESCE(PredComplDate,'31/12/2099'))='31/12/2099' THEN NULL
ELSE MAX(PredComplDate)
END AS LatestPredComplDate
FROM mytable33
GROUP BY [Reference Number],Predecessors
The expected result is NULL
for LastestPredComplDate
也许您可以将两个子句放在窗口函数中,如下所示(如果只是为了清晰起见):
MAX(CASE WHEN LEN(Predecessors)>0 THEN NULL ELSE PredComplDate END) AS LatestPredComplDate
Eventually, I found out the problem. The date (stored as NVARCHAR) format was the culprit. If you have another look at the first image that I posted you can see that the same dates have different formats. One is 04/12/2019
and the other is 4/12/2019
. It turns out the MAX
function would consider 4/12/2019
larger than 04/12/2019
and that would generate different results.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.