3

我需要编写一份关于 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 来开发查询。

4

3 回答 3

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

然后,您可以从statusto获得外键约束billtable。这将确保数据不能插入billtable,除非有相应的 key in status

然后,您的查找将始终有效。status但是,如果没有正确填充表,则插入失败的“代价”是。

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

于 2012-09-28T12:58:23.453 回答
1

你只需要联合所有

your first query
Union all
your Second query
union all
your third query
于 2012-09-28T12:41:35.740 回答
0

只需在您的查询之间添加 UNION 即可。

于 2012-09-28T12:42:40.953 回答