我最近不得不遇到sql查询,尽管这不是我的专长。以下查询是我使用的查询:我的问题是,如果该行的计数(1)= 0,则不会显示该行。第一个查询是第二个查询的演变,如果值为0,则显然会显示该行。由于需要大量的代理商代码,因此该演变是必要的,这可以使一切变得更快,并且不对n个代码的代理商执行n次查询。 >
SELECT
rollout.id AS 'RowNumber',
rollout.AgencyCode,
COUNT(1) AS 'NumberOfTitleAgnecy',
SUM(COUNT(1)) OVER() AS 'SumOfTitle'
FROM STAGINGTITLE AS ST
INNER JOIN (
VALUES
(1,'000001'),
(2,'000002'),
(3,'000003')
) AS rollout (id, CodAgency)
ON ST.AgencyCode = rollout.CodAgency
WHERE ST.ExternalId IS NULL
AND ST.TitleState = 'BackWard'
GROUP BY rollout.id, rollout.CodAgency
ORDER BY rollout.id
SELECT COUNT(1)
FROM STAGINGTITLE AS ST
WHERE ST.AgencyCode = '000001'
AND ST.ExternalId IS NULL
AND ST.TitleState = 'BackWard'
您对如何修改第一个查询以使行数显示(1)= 0有建议吗?
编辑:预期输出
RowNumber | AgencyCode | NumberOfTitleAgnecy | SumOfTitle |
-----------------------------------------------------------
1 | 000001 | 100 | 300 |
2 | 000002 | 0 | 300 |
3 | 000003 | 150 | 300 |
4 | 000004 | 50 | 300 |
答案 0 :(得分:0)
使用LEFT JOIN
:
SELECT rollout.id AS RowNumber,
rollout.CodAgency,
COUNT(st.AgencyCode) AS NumberOfTitleAgnecy,
SUM(COUNT(st.AgencyCode)) OVER () AS SumOfTitle
FROM (VALUES (1, '000001'), (2, '000002'), (3, '000003')
) rollout(id, CodAgency) LEFT JOIN
STAGINGTITLE ST
ON ST.AgencyCode = rollout.CodAgency AND
ST.ExternalId IS NULL AND ST.TitleState = 'BackWard'
GROUP BY rollout.id, rollout.CodAgency
ORDER BY rollout.id;
注意:
WHERE
子句被移到ON
子句中,因此LEFT JOIN
不会变成INNER JOIN
。COUNT()
现在正在计算匹配数,因此它可以返回0
。ST
的别名是固定的。CodAgency
的引用是固定的。