我有两个表连接以显示第一个表的计数值,我写了一个像这样的查询
我有一个表格,其中包含名为[PEBPC]的类别,其中包含3个生产者类别
USE [P1OTP]
SELECT pe.[ID] AS [No] ,pe.[NAME] AS [ProducerType] ,coalesce(COUNT(CASE tp.[NewProducer] WHEN 0 THEN 1 ELSE NULL END),0) AS [NewProducers] ,coalesce(COUNT(CASE tp.[NewProducer] WHEN 1 THEN 1 ELSE NULL END),0) AS [ExistProducer] ,coalesce(COUNT(tp.[NewProducer]),0) AS [Total] FROM [TPDCS] LEFT JOIN [PEBPC] pe ON pe.[ID] = tp.[estbProducerID] WHERE 1 = 1 AND tp.[OrganizationAddrProvince] IS NOT NULL AND tp.[OrganizationAddrProvince] = '81' AND tp.[libDocumentID] IN(SELECT [ParentID] FROM [TPDTS] WHERE [CategoryID] IS NOT NULL) > GROUP BY pe.[ID] ,pe.[NAME] ORDER BY pe.[ID]
当这个查询运行时,它只显示2个类别,因为这个省只有1个和2个类别
No Type of Producer NewProducer ExistProducer Total
1 Citizen Producer 102 0 102
2 sole proprietorship 45 0 45
我尝试了合并,计数或可以返回0的东西,但它不起作用
我需要他们像这样返回
No Type of Producer NewProducer ExistProducer Total
1 Citizen Producer 102 0 102
2 sole proprietorship 45 0 45
3 SME Producer 0 0 0
答案 0 :(得分:0)
这个怎么样?使用PEBPC
作为主表,然后将其加入TPDCS
。请注意,我在JOIN部分中移动了所有WHERE条件:
SELECT
pe.[ID] AS [No]
,pe.[NAME] AS [ProducerType]
,COALESCE(COUNT(CASE tp.[NewProducer] WHEN 0 THEN 1 ELSE NULL END),0) AS [NewProducers]
,COALESCE(COUNT(CASE tp.[NewProducer] WHEN 1 THEN 1 ELSE NULL END),0) AS [ExistProducer]
,COALESCE(COUNT(tp.[NewProducer]),0) AS [Total]
FROM [PEBPC] pe
LEFT JOIN [TPDCS] tp ON pe.[ID] = tp.[estbProducerID]
AND tp.[OrganizationAddrProvince] IS NOT NULL
AND tp.[OrganizationAddrProvince] = '81'
AND tp.[libDocumentID] IN(SELECT [ParentID] FROM [TPDTS] WHERE [CategoryID] IS NOT NULL)
GROUP BY pe.[ID], pe.[NAME]
ORDER BY pe.[ID]