sql server 2008:结合两个复杂的查询

时间:2010-11-05 17:45:01

标签: sql sql-server

这里有一个查询只返回一个名为datapath的列:

SELECT  --assumes number not at end of string
    LEFT(startOf, PATINDEX('%[^0-9]%', startof)-1)
FROM
    (
    SELECT  --assumed 3 digits minimum
        SUBSTRING(datapath, PATINDEX('%[0-9][0-9][0-9]%', datapath), 8000) AS startOf
    FROM
       (select datapath from batchinfo where LEN(datapath)>3) as bar
    ) foo

下面这个select语句中的另一个单词,而不是select datapath,我想运行上面的sql语句

SELECT reporttime,
                    datapath,
                    finalconc, 
                    instrument 
                    FROM batchinfo  
                    JOIN qvalues ON batchinfo.rowid = qvalues.rowid
                    WHERE compound = 3 AND name = "hey"
                   AND batchinfo.instrument = 44 
                   AND batchinfo.reporttime LIKE '10/%/2010%'";

2 个答案:

答案 0 :(得分:3)

SELECT reporttime,
                    datapath,
                    finalconc, 
                    instrument 
      FROM

(
SELECT  --assumes number not at end of string
    LEFT(startOf, PATINDEX('%[^0-9]%', startof)-1) AS datapath, --correct?
    rowid, instrument , reporttime 
FROM
    (
    SELECT  --assumed 3 digits minimum
        SUBSTRING(datapath, PATINDEX('%[0-9][0-9][0-9]%', datapath), 8000) AS startOf,
        rowid, instrument , reporttime
    FROM
       batchinfo --don't need LEN check. PATINDEX will do that implicitly
    ) foo

) batchinfo  
                    JOIN qvalues ON batchinfo.rowid = qvalues.rowid
                    WHERE compound = 3 AND name = "hey"
                   AND batchinfo.instrument = 44 
                   AND batchinfo.reporttime LIKE '10/%/2010%'";

答案 1 :(得分:0)

如果我正确读到这个,我认为您应该能够将第二个选择中的'datapath'列分配给您在第一个选择中选择的值,并将'startOf'替换为您的值选择startOf。

我认为会是这样的:

SELECT 
  reporttime, 
  'datapath' = LEFT(SUBSTRING(datapath, PATINDEX('%[0-9][0-9][0-9]%', datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(datapath, PATINDEX('%[0-9][0-9][0-9]%', datapath), 8000))-1) , 
  finalconc,  
  instrument  
FROM batchinfo   
JOIN qvalues ON batchinfo.rowid = qvalues.rowid 
WHERE compound = 3 AND name = "hey" 
AND batchinfo.instrument = 44  
AND batchinfo.reporttime LIKE '10/%/2010%'";