2010-10-15 95 views
2
UPDATE a 
    SET CountOfAA=dt.CountOf 
    FROM @MediaResurce a 
     INNER JOIN (SELECT 
         aa.Sku,ISNULL(COUNT(bb.sku),0) AS CountOf 
         FROM @MediaResurce      aa 
          LEFT OUTER JOIN @MediaResurce_Pics bb 
          ON aa.sku=bb.sku 
         WHERE somecol = 0 
         GROUP BY aa.Sku 
        ) dt ON a.sku=dt.sku 

/////////////SQL:我怎麼能把它變成一個查詢?

UPDATE a 
    SET CountOfBB=dt.CountOf 
    FROM @MediaResurce a 
     INNER JOIN (SELECT 
         aa.Sku,ISNULL(COUNT(bb.sku),0) AS CountOf 
         FROM @MediaResurce      aa 
          LEFT OUTER JOIN @MediaResurce_Pics bb 
          ON aa.sku=bb.sku 
         WHERE somecol = 1 
         GROUP BY aa.Sku 
        ) dt ON a.sku=dt.sku 
+1

哦SQL Server,我多麼喜歡你的奇怪語法。 – vol7ron 2010-10-15 22:37:59

+0

哦上帝請有人幫助我這是給我一個恐慌發作 – wil 2010-10-15 23:05:29

回答

0

那麼你可以很容易地做到這一點作爲

UPDATE a 
SET CountOfAA=dt.CountOf, 
    CountOfBB=dt2.CountOf 
FROM @MediaResurce a 
    INNER JOIN (SELECT 
        aa.Sku,ISNULL(COUNT(bb.sku),0) AS CountOf 
        FROM @MediaResurce      aa 
         LEFT OUTER JOIN @MediaResurce_Pics bb 
         ON aa.sku=bb.sku 
        WHERE somecol = 0 
        GROUP BY aa.Sku 
       ) dt ON a.sku=dt.sku 
    INNER JOIN (SELECT 
        aa.Sku,ISNULL(COUNT(bb.sku),0) AS CountOf 
        FROM @MediaResurce      aa 
         LEFT OUTER JOIN @MediaResurce_Pics bb 
         ON aa.sku=bb.sku 
        WHERE somecol = 1 
        GROUP BY aa.Sku 
       ) dt2 ON a.sku=dt2.sku 

哪一個是懶惰和inneficient方法,其他方法可能是這樣的:

SUM(somecol) AS 'count where somecol=1' 
count(*) - SUM(somecol) AS 'count where somecol=0' 
... 
where somecol in (0,1) //only need if somecol can be something other than 0 or 1! 
+0

沒有抱歉,這是一個有點數據類型 – wil 2010-10-15 23:09:15

+0

所以它是兩個子查詢,並且這些集合將按順序排列,因爲它們對應子查詢? – wil 2010-10-15 23:10:41

1

這應該是你在找什麼:

UPDATE a 
SET 
    CountOfAA = dt.CountOfAA, 
    CountOfBB = dt.CountOfBB 
FROM @MediaResurce a 
INNER JOIN (
    SELECT 
    SUM(
     case somecol 
     when 0 then 1 
     else 0 
     end 
    ) AS CountOfAA, 
    SUM(
     case somecol 
     when 1 then 1 
     else 0 
     end 
    ) AS CountOfBB 
    FROM @MediaResurce aa 
    LEFT OUTER JOIN @MediaResurce_Pics bb 
     ON aa.sku=bb.sku 
) dt ON a.sku=dt.sku 

而不是兩個單獨的查詢來計算每個實例,您可以SUM「1」或「0」根據您的「somecol」的要求。

相關問題