SQL在不同的行中显示来自同一表的不同数据

时间:2010-11-03 11:25:00

标签: sql subquery

我正在尝试从一个视图(v_gs_softwarefile)获取我们的库存软件(在本例中为SCCM)中的系统列表,但具有多个条件。在这种特殊情况下,我需要所有系统(SCCM调用唯一标识符“ResourceID”,所以我只是坚持那个)没有iexplore版本> 8,另一边有一个saplogon.exe,其确切版本为'7100.3.13.1045'。

版本1(问题:如何输出saplogon.exe结果的文件名和文件版本?)

SELECT DISTINCT
    t1.ResourceID
    ,t1.FileName
    ,t1.FileVersion    
FROM
    v_GS_SoftwareFile as t1 
WHERE 
    (t1.filename = 'iexplore.exe'
    and
    t1.fileversion < '8.0')
    and
    t1.resourceid in (
        SELECT DISTINCT
            t2.resourceid
        FROM
            v_gs_softwarefile as t2
        WHERE
            t2.filename = 'saplogon.exe'
            and
            t2.fileversion ='7100.3.13.1045')

我设法在第二次尝试时得到了我的输出,但是对于我遇到的第1版的简单问题,结果SQL可能太复杂了

第2版:

declare @tab1 table (
    resourceid int,
    filename char(255),
    fileversion char(255)
    )

insert into @tab1(t1.resourceid,t1.filename,t1.fileversion)
select
    t1.resourceid,
    t1.FileName,
    t1.FileVersion    
    from v_GS_SoftwareFile as t1
where 
    t1.filename = 'iexplore.exe'
    and
    t1.fileversion < '8'

select distinct
    temp.resourceid,
    temp.filename as 'IE',
    temp.fileversion as 'IE ver',
    orig.filename as 'SAP',
    orig.fileversion as 'SAP ver'
from @tab1 as temp 
    inner join v_gs_softwarefile as orig on orig.resourceid = temp.resourceid
where
    orig.filename = 'saplogon.exe'
    and
    orig.fileversion = '7100.3.13.1045'
order by temp.resourceid

结果如下:

resourceid | IE | IE ver | SAP | SAP ver
2542 |iexplore.exe | 6.00.2900.5512 (xpsp.080413-2105) | saplogon.exe | 7100.3.13.1045
1544 |iexplore.exe | 7.00.5730.11 (winmain(wmbla).061017-1135) | saplogon.exe | 7100.3.13.1045

2 个答案:

答案 0 :(得分:1)

你的第二次尝试对我来说非常好。如果是我,我会通过消除临时表并使用几个子选择来简化这一点,因此查询将转换为:

select distinct temp.resourceid, 
                temp.filename as 'IE', 
                temp.fileversion as 'IE ver', 
                orig.filename as 'SAP', 
                orig.fileversion as 'SAP ver' 
  from (select resourceid,
               FileName,
               FileVersion
          from v_GS_SoftwareFile
          where filename = 'iexplore.exe' and
                fileversion < '8' ) as temp
inner join (select resourceid,
                   filename,
                   fileversion
              from v_gs_softwarefile
              where filename = 'saplogon.exe' and 
                    fileversion = '7100.3.13.1045') as orig
  on orig.resourceid = temp.resourceid
order by temp.resourceid 

我还怀疑可能不需要主查询的DISTINCT。尝试使用和不使用DISTINCT进行查看。

分享并享受。

答案 1 :(得分:1)

或者只是自我加入...

select t1.resourceid,
    t1.filename as 'IE',
    t1.fileversion as 'IE ver',
    t2.filename as 'SAP',
    t2.fileversion as 'SAP ver'
from v_GS_SoftwareFile as t1
    inner join v_gs_softwarefile as t2 on t2.resourceid = t1.resourceid
where
    (t2.filename = 'saplogon.exe'
    and
    t2.fileversion = '7100.3.13.1045')
    AND 
    (t1.filename = 'iexplore.exe'
    and t1.fileversion < '8')
order by t1.resourceid