我想编写摘要查询并将结果显示在单个表中

时间:2012-09-28 12:37:58

标签: sql sql-server tsql ssms

我需要编写3个不同状态值的摘要报告,每个状态都有一个计数和一个数量列,结果显示在一个表中。例如,输出将如下所示:

enter image description here

生成每行代码(在单个输出中)的查询是:

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

这会产生三个结果,如:

enter image description here

我正在使用SQL Server数据库和SSMS来开发查询。

3 个答案:

答案 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

然后,您可以拥有从statusbilltable的外键约束。这将确保无法将数据插入billtable,除非status中有相应的密钥。

您的查找将始终有效。但是,如果status表未正确填充,则插入失败的“成本”。

fact-tabledimension-table结构是关系数据库设计的基础。

答案 1 :(得分:1)

你只需加入所有

your first query
Union all
your Second query
union all
your third query

答案 2 :(得分:0)

只需在查询之间添加UNION。