我们有两个表,Status和Main。
状态表:
statusId int pk
Status nvarchar(100)
示例数据
1 Open
2 Cancelled
3 Under Review
4 Awarded
5 Archived
6 Closed
7 Removed
8 Library CM Subcontractor
9 Property Sales
主表:
statusid int fk to Status table
Type nvarchar(50)
示例数据
StatusID Type
1 Bid
1 Quote
1 RFP
我们正在尝试从主表中获取当前类型的计数和状态表中的状态计数,并按以下格式显示结果:
Current [count]
Current Bid [count]
Current RFP [count]
Sole Source [count]
Library CM Subcontracting [count]
Current Quotes [count]
Property Sales [count]
Closed [count]
Cancelled [count]
Under Review [count]
Awarded [count]
Archives [count]
方括号中的单词计数表示特定字段名称的记录总数。
到目前为止,我的代码会从主表中生成当前出价,当前报价和当前RFP的数量。
但是,我的状态计数正在重复。
以下是我正在使用的代码:
select
case when status.status ='Open' then Main.Type else status.status end as Name
, count(*) as total
from Main
inner join status on Main.Bidstatus = status.statusid
group by
case when status.status ='Open' then Main.Type else status.status end
, Main.Type
知道如何修改代码以产生唯一的记录计数吗?
答案 0 :(得分:0)
您的问题仍不明确,您的要求也在不断变化。但是,如果您需要主类型记录的总计数和子状态记录的总计数,您可以根据需要使用以下查询分隔或UNIONed:
SELECT Main.Type Name ,
COUNT( * )AS Count
FROM Main
INNER JOIN status ON Main.Bidstatus = status.statusid
GROUP BY Main.Type
--optional:
--UNION
SELECT status.statusid Name ,
COUNT( * )AS Count
FROM Main
INNER JOIN status ON Main.Bidstatus = status.statusid
GROUP BY status.statusid