2012-09-14 54 views
0

在較大的查詢中有以下子查詢。我收到一個錯誤「子查詢返回了超過1個值」。我不知道我該如何解決這個問題,並且仍然有兩個查詢的結果發生分歧。我正在使用SQL Server 2005.子查詢返回了多個值錯誤

謝謝。

SELECT 
    sample_fields, -- some fields here 
    (SELECT 
     c1/c2 AS department_occupancy_rate -- doing division of results of both queries 
    FROM 
     property as c 
     JOIN (
       SELECT store_id, cast(count(*) as decimal(10,2)) AS c1 
       FROM property 
       WHERE 
        non_ha =1 
       AND property_type LIKE '%587%'  
       GROUP BY store_id 
      ) AS sub1 
      ON c.store_id = sub1.store_id 
      JOIN (
       SELECT store_id, cast(count(*) as decimal(10,2)) AS c2 
       FROM property 
       WHERE 
        property_type LIKE '%587%' 
       GROUP BY store_id 
      ) AS sub2 
      ON c.store_id = sub2.store_id 
     ) as results, 
FROM 
    sample_table -- a table here 
    INNER JOIN sample_table1 
    ON sample_table2 -- joining here 
GROUP BY sample_field -- grouping 
+0

嘗試SELECT TOP 1 ...或SELECT ... LIMIT 1取決於你的SQL風格。 –

+2

您是否嘗試過重構該SQL?這很漂亮... –

+0

你檢查了你的查詢的最後一個連接 - > INNER JOIN sample_table1 ON sample_table2? – Luftwaffe

回答

2

那麼,這是不清楚你想要做什麼,因爲在其與外部查詢內部查詢不相關條件。我想這應該是一個store_id,如果是的話,你應該這樣做:

SELECT sample_fields,-- some fields here 
     results.department_occupancy_rate 
FROM sample_table -- a table here 
     INNER JOIN sample_table1 
       ON sample_table2 -- joining here 
     JOIN (SELECT c.store_id, 
        c1/c2 AS department_occupancy_rate 
      -- doing division of results of both queries 
      FROM property AS c 
        JOIN (SELECT store_id, 
           Cast(Count(*) AS DECIMAL(10, 2)) AS c1 
          FROM property 
          WHERE non_ha = 1 
           AND property_type LIKE '%587%' 
          GROUP BY store_id) AS sub1 
         ON c.store_id = sub1.store_id 
        JOIN (SELECT store_id, 
           Cast(Count(*) AS DECIMAL(10, 2)) AS c2 
          FROM property 
          WHERE property_type LIKE '%587%' 
          GROUP BY store_id) AS sub2 
         ON c.store_id = sub2.store_id) AS results 
     ON (sample_table.store_id = results.store_id) 
GROUP BY sample_field -- grouping