2013-07-01 85 views
0

我習慣於使用mysql時,如果可以做到這一點,沒有任何問題。我想在SQL Server中運行以下語句,但它沒有看到列C_COUNT如何比較SQL Server中的兩行

SELECT 
    A.customers AS CUSTOMERS, 
    (SELECT COUNT(ID) FROM Partners_customers B WHERE A.ID = B.PIID) AS C_COUNT 
FROM Partners A 
WHERE CUSTOMERS <> [C_COUNT] 

是否有可能利用在SELECT地區的任何數學運算一樣

SELECT (CUSTOMERS - C_COUNT) AS DIFFERENCE 

回答

5

SQL Server不會允許你在WHERE子句中使用別名。你必須有這樣的事情:

SELECT *, Customers - C_COUNT "Difference" 
FROM (
    SELECT 
    A.customers AS CUSTOMERS, 
    (SELECT COUNT(ID) 
    FROM Partners_customers B WHERE A.ID = B.PIID) 
    AS C_COUNT FROM Partners A 
) t 
WHERE CUSTOMERS <> [C_COUNT] 

或者,更好的是,消除了內聯計數:

select A.customers, count(b.id) 
FROM Partners A 
LEFT JOIN Partners_customers B ON A.ID = B.PIID 
Group By A.ID 
having a.customers <> count(b.id) 
+0

或者:複製/粘貼相關的子查詢。 –

0
WITH A AS 
(
    SELECT 
     A.customers AS CUSTOMERS, 
     (SELECT COUNT(ID) FROM Partners_customers B WHERE A.ID = B.PIID) AS C_COUNT 
    FROM Partners A 
    WHERE CUSTOMERS <> [C_COUNT] 
) 
SELECT 
    *, 
    (CUSTOMERS - C_COUNT) AS DIFFERENCE 
FROM A 
0

沒有經過充分測試....

(select * from TabA 
minus 
select * from TabB) -- Rows in TabA not in TabB 
union all 
( 
select * from TabB 
minus 
select * from TabA 
) -- rows in TabB not in TabA