如何使子查询正确

时间:2011-03-11 22:25:57

标签: sql ms-access subquery

嘿伙计们,我在SQL中遇到子查询的问题。我正在使用MS Access 2010并编写sql。

SELECT vak.Name, COUNT(vak.amount) AS [First], COUNT(vak2.amount2) AS [Second]    
FROM  
(SELECT kon.Name, (Count(icv.CV_ID) / Count(icv.CV_ID)) AS amount  
 FROM (kon INNER JOIN v ON kon.K_ID = v.K_ID) INNER JOIN icv ON v.Vak_ID = icv.Vak_ID  
 GROUP BY v.Vak_ID, kon.Name) AS vak,  
(SELECT kon.Name, COUNT(v.Vak_ID) AS amount2  
 FROM (kon INNER JOIN v ON kon.K_ID = v.K_ID) INNER JOIN icv ON v.Vak_ID = icv.Vak_ID  
 GROUP BY kon.Name) AS vak2  
GROUP BY vak.Konkursa_Nosaukums

当我在数据表视图中检查它时,两列是相同的。 “First”中有6行,其值为12,12,6,12,6,6。“Second”列中的值相同。当我将此代码拆分为2个并为测试创建2个新查询时,“First”列显示值2,2,1,2,1,1,第二个查询的值为3,3,1,2,1, 1。这两个列在它们分开时都具有正确的值,但是当我将它们组合在一起时,一些未知值看起来像12(我不知道它在哪里取这样的数字如12)。我放线时 WHERE vak.amount = vak2.amount2在最后一行之前它在两列中显示2,2,1,2,1,1。我想它只需要从第一个子查询或其他东西。

如何正确地创建这些子查询,以便它们显示与单独编写时相同的值?

2 个答案:

答案 0 :(得分:0)

SELECT vak.Name, vak.amount AS [First], vak2.amount2 AS [Second]
FROM  
(SELECT kon.Name, (Count(icv.CV_ID) / Count(icv.CV_ID)) AS amount  
 FROM (kon INNER JOIN v ON kon.K_ID = v.K_ID) INNER JOIN icv ON v.Vak_ID = icv.Vak_ID  
 GROUP BY v.Vak_ID, kon.Name) AS vak,
(SELECT kon.Name, COUNT(v.Vak_ID) AS amount2  
 FROM (kon INNER JOIN v ON kon.K_ID = v.K_ID) INNER JOIN icv ON v.Vak_ID = icv.Vak_ID  
 GROUP BY kon.Name) AS vak2  
WHERE vak.Name = van2.Name

答案 1 :(得分:0)

我认为你错过了一个加入条件并且在适当的群体中... ...

SELECT vak.Name, vak.amount AS [First], vak2.amount2 AS [Second]
FROM  
(SELECT kon.Name, (Count(icv.CV_ID) / Count(icv.CV_ID)) AS amount  
 FROM (kon INNER JOIN v ON kon.K_ID = v.K_ID) INNER JOIN icv ON v.Vak_ID = icv.Vak_ID  
 GROUP BY v.Vak_ID, kon.Name) AS vak,
(SELECT kon.Name, COUNT(v.Vak_ID) AS amount2  
 FROM (kon INNER JOIN v ON kon.K_ID = v.K_ID) INNER JOIN icv ON v.Vak_ID = icv.Vak_ID  
 GROUP BY kon.Name) AS vak2  
WHERE vak.Name = van2.Name