27,579
社区成员
发帖
与我相关
我的任务
分享
CREATE INDEX ix_A_insertTime ON A(insertTime)
--创建索引是提高效率的最快办法
--表A 的 pid 上如果没有索引, 应该创建:
CREATE CLUSTERED INDEX ix_A_pid ON A(pid)
--表B 的 pid 上如无索引, 应该创建
CREATE CLUSTERED UNIQUE ix_B_pid ON B(pid) --B表中 pid 应该是唯一的吧?
--查询类似下面即可,不需要什么 cte
SELECT
A.pid
,A.[name]
,B.salary
FROM A INNER JOIN B ON A.pid=B.pid
WHERE A.Intime BETWEEN '2018-11-01' AND '2018-11-31 23:59:59'
WITH temp AS
(
SELECT pid,name,salary FROM A
WHERE
( @thisDate='thisYear' AND Intime BETWEEN '2018-11-01' AND '2018-11-01')
OR (@thisDate='tLASTYear' AND 其他字段=1) --通过这种形式实现
)
SELECT * FROM xst05
--所有关于条件的逻辑,在外面写好,不要放在 sql 里面。
--放外面更易懂,而且不会干扰 sql 的执行效率
DECLARE @beginTime DATETIME,@endTime DATETIME,@thisDate NVARCHAR(50)
SET @thisDate='thisYear'
IF @thisDate='thisYear'
BEGIN
SET @beginTime='2018-11-01'
SET @endTime='2018-12-01'
END
;WITH temp AS
(
SELECT pid,
NAME,
salary
FROM A
WHERE Intime BETWEEN @beginTime AND @endTime
)
SELECT *
FROM xst05 INNER JOIN temp ON xst05.pid=temp.pid