You are here: Re: SQL Query Help « MsSQL Server « IT news, forums, messages
Re: SQL Query Help

Posted by Erland Sommarskog on 11/23/05 00:32

Will Chamberlain (will.chamberlain@devdex.com) writes:
> I am working on queries for a SQL database. I have much experience with
> Access and am trying to ween myself off of it. The query I am working
> on now is supposed to return a set of data like the following:
>
> LatestVersion(Ver)/VersionUpdate(Update)/Location(SheetNumber)
> A/aa1/3
>
> This works fine except for some of the products in the database don't
> have these values attributed to them. I am using the following SQL
> query:
>
> SELECT Max(COALESCE(Sheet.Ver, 'NONE')) AS MaxOfVer,
> Max(COALESCE(Update.Update, 0)) AS MaxOfUpdate, Sheet.SheetNumber FROM
> Drawings INNER JOIN (Update INNER JOIN
> Sheet ON Update.RecordID = Sheet.RecordID) ON Drawings.Drawing =
> Sheet.Drawing WHERE (Sheet.Drawing = 'XXXXX') AND
> (Sheet.SheetType = 'SH') GROUP BY Sheet.Drawing, Sheet.SheetType,
> Sheet.SheetNumber
>
>
> How can I edit this string to return either all 3 of the fields I need,
> or return all of 3 of the fields with value = NONE if there are no
> results. Is it possible to wrap a COALESCE around the whole query
> string?

I'm not sure this makes 100% sense to me. First of all in your current
query you have:

Max(COALESCE(Sheet.Ver, 'NONE'))

Say that there are three entries, and one has the value A1, one the value B1
and one has NULL in Sheet.Ver. You will get NONE as the result. But say now
that a row with the value R1 is added. Now your query will return R1. This
seems funny to me.

As for returning 'NONE' in all three columns when there are no rows
round that fullfils the conditions in the WHERE clause, this also appears
funny as SheetNumber appears to be numeric.

But to get what you want, you could insert the data into a temp table,
and then:

IF NOT EXISTS (SELECT * FROM #temp)
INSERT #temp VALUES ('NONE', 'NONE', 'NONE')
SELECT * FROM #temp

But I am not really sure that is something you should do. Better let
the client handle the fact that there were no hits.

--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация