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
/////////////
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
答案 0 :(得分: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
根据“somecol”的要求,您可以使用SUM“1”或“0”代替两个单独的查询来计算每个实例。
答案 1 :(得分: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
这是懒惰和无效的方式,另一种方法可能是这样的:
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!