查询多表数据

时间:2011-04-03 04:32:04

标签: sql-server-2005

这是我试图执行的查询,但它说无法找到所有表的存储过程。

alltable(SELECT转换(datetime,转换(char(10),[Date / Time],101))[Date / Time],[Through],[Number Received] 来自交易 UNION ALL

SELECT转换(日期时间,转换(字符(10),[日期/时间],101))[日期/时间],[通过],[收到的金额] 来自DTH UNION ALL

SELECT转换(日期时间,转换(字符(10),[日期/时间],101))[日期/时间],[通过],[收到的金额] 来自公用事业 UNION ALL

SELECT转换(日期时间,转换(字符(10),[日期/时间],101))[日期/时间],[通过],[收到的金额] 来自移动 UNION ALL

SELECT转换(日期时间,转换(字符(10),[日期/时间],101))[日期/时间],[通过],[收到的金额] 来自ISP) SELECT转换(datetime,convert(char(10),[Date / Time],101))[Date / Time],[Through],SUM([Amount Received]) 来自alltable GROUP BY转换(datetime,convert(char(10),[Date / Time],101)),[Through]

2 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

with AllTables as (
    select dateadd(day, 0, datediff(day, 0, [Date/Time])) as Date, Service, AmountReceived from Table1 union all
    select dateadd(day, 0, datediff(day, 0, [Date/Time])) as Date, Service, AmountReceived from Table2 union all
    select dateadd(day, 0, datediff(day, 0, [Date/Time])) as Date, Service, AmountReceived from Table3 union all
    select dateadd(day, 0, datediff(day, 0, [Date/Time])) as Date, Service, AmountReceived from Table4 union all
    select dateadd(day, 0, datediff(day, 0, [Date/Time])) as Date, Service, AmountReceived from Table5
)
select Date, Service, sum(AmountReceived) as AmountReceived
from AllTables
group by Date, Service

请确保使用union all而非union

答案 1 :(得分:0)

这可能效率不高但它会起作用......首先......

从每个表中选择你想要的3个字段并将它们组合在一起...作为一个视图...然后你在视图上求和/分组......

离.... 创建视图组合 如 从table1中选择DateField,Service,AmountRecieved 联盟 从table2中选择DateField,Service,AmountRecieved 联盟 从table3中选择DateField,Service,AmountRecieved ...

选择sum(amountREcieved),DAteField,Service DAteField,服务小组

GL