将结果分为两个查询

时间:2010-11-01 00:42:57

标签: sql sql-server-2005

我花了大约4个小时,但我无法找到答案,我希望结果像

不合格品

somefilename1.txt - 已拒绝(如果没有文件,则表示否则来自其他表达式(否 - 无效) - 查询1) somefilename2.txt - 上一个(如果没有文件,那么来自else表达式No(No - Valid)-Query 2)

我不明白我该怎么做,我使用union all还是case表达式。请帮助我。

QUERY1:

if exists (select NULL from table1 where Column1 = 'File1')
    select distinct Column1 +'-'+ 'Rejected' as 'Rejects' from table1
    where Column1 = 'File1'
else 
    select 'No' as 'Invalid'

QUERY2:

if exists (select NULL from table1 where Column1 = 'File2')
    select distinct Column1 +'-'+ 'Previous' as 'Rejects' from table1
    where column1 = 'File2'
else 
    select 'No' as 'valid'

由于

2 个答案:

答案 0 :(得分:0)

根据评论,看看是否会返回您要查找的内容。

如果表格中没有记录,则结果为No Input File

当存在记录时,每行都使用CASE语句进行评估。

--drop table table1

create table table1
(SubjectArea varchar(255)
, SrcFileName varchar(255))

insert into table1
select 'UaqaFacetsPvs','somefilename1.txt'
union select 'UaqaFacetsRjct','somefilename2.txt'
union select null,null
union select null,'somefilename2.txt'

IF EXISTS(SELECT NULL FROM table1 WHERE SubjectArea in ('UaqaFacetsRjct','UaqaFacetsPvs'))
    SELECT DISTINCT SrcFileName
     + ' - ' + 
     CASE SubjectArea 
        WHEN 'UaqaFacetsPvs' THEN 'FacetsPvsFile'
        WHEN 'UaqaFacetsRjct' THEN 'FacetsRjctFile'
        ELSE ''
      END AS Result
    FROM table1
    WHERE SubjectArea in ('UaqaFacetsRjct','UaqaFacetsPvs')
ELSE SELECT 'No input file' AS Result

IF会返回此信息:

Result
---------------------------------
somefilename1.txt - FacetsPvsFile
somefilename2.txt - FacetsRjctFile

答案 1 :(得分:0)

经过所有的斗争,我终于弄明白了。我拿出了IF..ELSE。我在两个查询中都创建了临时表INSERT INTO .. SELECT DISTINCT。所以它就像......

TRUNCATE TABLE #TEMP;

INSERT INTO #TEMP SELECT DISTINCT...... (Query 1);

INSERT INTO #TEMP SELECT DISTINCT...... (Query 2);

SELECT * FROM #TEMP;

特别感谢Vinnie。感谢你的帮助。