34,587
社区成员
发帖
与我相关
我的任务
分享
--借用 #1 版主数据
USE tempdb
GO
--删除后面要创建的视图
IF OBJECT_ID('dbo.view_A_B') IS NOT NULL
DROP VIEW dbo.view_A_B
GO
--测试数据
if not object_id(N'Tempdb..A') is null
drop table A
GO
GO
Create table A([单据内码] int,[是否确认] nvarchar(23))
SET NOCOUNT ON
Insert A
select 1001,N'YES' union all
select 1002,N'NO' union all
select 1003,N'YES' union all
select 1004,N'NO'
GO
if not object_id(N'Tempdb..B') is null
drop table B
Go
Create table B([单据内码] int,[数量] int,[是否审核] nvarchar(23))
SET NOCOUNT ON
Insert B
select 1001,100,N'YES' union all
select 1001,100,N'NO' union all
select 1001,100,N'YES'
Go
--测试数据结束
--创建索引视图. 只要能创建成功, 你的效率就能提高
CREATE VIEW dbo.view_A_B
WITH SCHEMABINDING
AS
Select A.单据内码,sum(B.数量) AS 数量
from dbo.A INNER JOIN dbo.B
ON A.单据内码 = B.单据内码 AND A.是否确认='YES' AND B.是否审核='YES'
GROUP BY A.单据内码
GO
SELECT * FROM view_A_B
你看一下结果, 是否是你要的。
如果是你要的, 这种设计的效率是最高的。
因为这个聚合的结果放在了索引视图(相当于真实的表,占存储空间)
你查询时就是秒出的。--测试数据
if not object_id(N'Tempdb..#A') is null
drop table #A
Go
Create table #A([单据内码] int,[是否确认] nvarchar(23))
Insert #A
select 1001,N'YES' union all
select 1002,N'NO' union all
select 1003,N'YES' union all
select 1004,N'NO'
GO
if not object_id(N'Tempdb..#B') is null
drop table #B
Go
Create table #B([单据内码] int,[数量] int,[是否审核] nvarchar(23))
Insert #B
select 1001,100,N'YES' union all
select 1001,100,N'NO' union all
select 1001,100,N'YES'
Go
--测试数据结束
SELECT t1.单据内码,t2.数量 FROM (
Select * from #A WHERE 是否确认='YES'
)t1 JOIN (
SELECT 单据内码, 数量 FROM #B WHERE 是否审核='YES'
)t2
ON t2.单据内码 = t1.单据内码