我需要编写3个不同状态值的摘要报告,每个状态都有一个计数和一个数量列,结果显示在一个表中。例如,输出将如下所示:
生成每行代码(在单个输出中)的查询是:
select case when status_key = '2' then 'Paid' else '' end as 'Status'
, COUNT(BillNo) as [Count]
, SUM(amtpd) as [Amount Paid]
from billtable
where client = 101
and status_key = '2'
group by status_key
select case when status_key = '1' then 'Queued' else '' end as 'Status'
, COUNT(BillNo) as [Count]
, SUM(amtpd) as [Amount Paid]
from billtable
where client = 101
and status_key = '1'
group by status_key
select case when status_key = '4' then 'Hold' else '' end as 'Status'
, COUNT(BillNo) as [Count]
, SUM(amtpd) as [Amount Paid]
from billtable
where client = 101
and status_key = '4'
group by status_key
这会产生三个结果,如:
我正在使用SQL Server数据库和SSMS来开发查询。
答案 0 :(得分:5)
不需要工会。
使用WHERE仅过滤所需的status_keys,然后展开CASE语句以从数字重新编码为单词。
select
case when status_key = '2' then 'Paid'
when status_key = '1' then 'Queued'
when status_key = '4' then 'Hold'
else 'Error!' end AS [Status],
COUNT(BillNo) AS [Count],
SUM(amtpd) AS [Amount Paid]
from
billtable
where
client = 101
AND status_key IN ('1','2','4')
group by
status_key
编辑使用维度表
的修改示例select
status.description AS [Status],
COUNT(bill_table.BillNo) AS [Count],
SUM(bill_table.amtpd) AS [Amount Paid]
from
billtable
inner join
status
on billtable.status_key = status.key
where
bill_table.client = 101
AND bill_table.status_key IN ('1','2','4')
group by
status.description
然后,您可以拥有从status
到billtable
的外键约束。这将确保无法将数据插入billtable
,除非status
中有相应的密钥。
您的查找将始终有效。但是,如果status
表未正确填充,则插入失败的“成本”。
此fact-table
和dimension-table
结构是关系数据库设计的基础。
答案 1 :(得分:1)
你只需加入所有
your first query
Union all
your Second query
union all
your third query
答案 2 :(得分:0)
只需在查询之间添加UNION。