【问题标题】:How to create a Table from multiple queries如何从多个查询创建表
【发布时间】:2018-06-13 20:22:40
【问题描述】:

我正在尝试创建一个表格,计算两个不同表格中的项目,以获得如下总计和小计:

(select count(*) from ccustomer AS TotalCustomers)    
(select count(*) from ccustomer where floating = 0 AS ActiveCustomers),    
(select count(*) from ccustomer where floating = 1 AS FloatingCustomers),    
(select count(*) from pproperty AS TotalProperties)    
(select count(*) from pproperty where occcustno = 0 and propstat <> 'de' AS VoidProperties),    
(select count(*) from pproperty where occcustno = 0 and propstat = 'de' AS DemolishedProperties),    
(select count(*) from pproperty where occcustno <> 0 AS OccupiedProperties);

首先,这些查询在第 2+3 行(第 1 行的小计)和 5+6+7(4 的小计)中返回“AS”附近的语法问题。我无法克服这一点,因为我每次都尝试使用或不使用括号等重新格式化。

消息 156,级别 15,状态 1,行 2
关键字“AS”附近的语法不正确。
消息 156,第 15 级,状态 1,第 3 行
关键字“AS”附近的语法不正确。
消息 156,第 15 级,状态 1,第 5 行
关键字“AS”附近的语法不正确。
消息 156,第 15 级,状态 1,第 6 行
关键字“AS”附近的语法不正确。
消息 156,第 15 级,状态 1,第 7 行
关键字“AS”附近的语法不正确。

我需要生成一个包含这些标题和总计/小计的表格,所以不知道这是否可行。我有一个前同事使用 NumberCheck 创建表创建的另一个查询,但它对我来说复制起来有点太复杂了(他不再在这里寻求帮助)。

任何帮助将不胜感激。 谢谢 利亚姆

【问题讨论】:

  • 你最后的括号需要在每一行的“as blah-blah”的左边。

标签: sql-server tsql sql-server-2014


【解决方案1】:

试试这个:

create table ccustomer(floating int)
create table pproperty(occcustno int, propstat nvarchar(50) )
insert into ccustomer values (1),(0),(1),(0),(1),(0),(1),(0),(1),(1)
insert into pproperty values (0,'de'), (1,'de'), (0,'de'), (0,'us'), (1,'de'), (1,'us'), (1,'de')

select
(select count(*) from ccustomer) AS TotalCustomers,
(select count(*) from ccustomer where floating = 0) AS ActiveCustomers,    
(select count(*) from ccustomer where floating = 1) AS FloatingCustomers,    
(select count(*) from pproperty ) AS TotalProperties,    
(select count(*) from pproperty where occcustno = 0 and propstat <> 'de') AS VoidProperties,    
(select count(*) from pproperty where occcustno = 0 and propstat = 'de') AS DemolishedProperties,    
(select count(*) from pproperty where occcustno <> 0) AS OccupiedProperties;

在脚本中我创建了一个示例输入场景:

结果:

【讨论】:

  • 嗨,安德里亚,非常感谢。我试过了,尽管我没有在我们的数据库中创建表的权限,但我们的 IT 人员使用它并且工作正常。干杯!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多