如何根据临时 table SQL Server 2008 R2 从一个 table 中提取数据?
How to pull data from one table based on a temp table SQL Server 2008 R2?
我目前的查询:
SELECT
E.FILEKEY,
(SELECT MAX(EFFDATE)
FROM
(SELECT B.FILEKEY, B.STATUS AS STATUS, B.EFFDATE
FROM TABLEB B
UNION
SELECT A.FILEKEY, A.STATUS2 AS STATUS, A.EFFDATE2 AS EFFDATE
FROM TABLEA A) C
WHERE C.EFFDATE <= '5/1/2011'),
A.STATUS
FROM
TABLE1 A
INNER JOIN
TABLE2 B ON A.FILEKEY = B.FILEKEY
GROUP BY
A.FILEKEY, A.STATUS
tableA
和 tableB
(table C) 的并集产生这些结果:
FILEKEY STATUS EFFDATE
----------------------------------------
1 0 2009-01-01 00:00:00.000
1 1 2010-01-01 00:00:00.000
1 0 2011-01-01 00:00:00.000
1 1 2012-01-01 00:00:00.000
1 0 2013-01-01 00:00:00.000
我知道我的查询是错误的,得出以下结果:
filekey (No column name) status
------------------------------------------
1 2011-01-01 00:00:00.000 1
我只是不确定如何使用关联的 effdate
提取正确的状态,而不会导致出现各种错误。
感谢您的帮助。
我想你正在寻找这样的东西。
SELECT TOP 1 *
FROM
(SELECT B.FILEKEY, B.STATUS AS STATUS, B.EFFDATE FROM TABLEB B
UNION
SELECT A.FILEKEY, A.STATUS2 AS STATUS, A.EFFDATE2 AS EFFDATE FROM TABLEA A) C
WHERE C.EFFDATE <= '5/1/2011')
ORDER BY C.EFFDATE DESC
我目前的查询:
SELECT
E.FILEKEY,
(SELECT MAX(EFFDATE)
FROM
(SELECT B.FILEKEY, B.STATUS AS STATUS, B.EFFDATE
FROM TABLEB B
UNION
SELECT A.FILEKEY, A.STATUS2 AS STATUS, A.EFFDATE2 AS EFFDATE
FROM TABLEA A) C
WHERE C.EFFDATE <= '5/1/2011'),
A.STATUS
FROM
TABLE1 A
INNER JOIN
TABLE2 B ON A.FILEKEY = B.FILEKEY
GROUP BY
A.FILEKEY, A.STATUS
tableA
和 tableB
(table C) 的并集产生这些结果:
FILEKEY STATUS EFFDATE
----------------------------------------
1 0 2009-01-01 00:00:00.000
1 1 2010-01-01 00:00:00.000
1 0 2011-01-01 00:00:00.000
1 1 2012-01-01 00:00:00.000
1 0 2013-01-01 00:00:00.000
我知道我的查询是错误的,得出以下结果:
filekey (No column name) status
------------------------------------------
1 2011-01-01 00:00:00.000 1
我只是不确定如何使用关联的 effdate
提取正确的状态,而不会导致出现各种错误。
感谢您的帮助。
我想你正在寻找这样的东西。
SELECT TOP 1 *
FROM
(SELECT B.FILEKEY, B.STATUS AS STATUS, B.EFFDATE FROM TABLEB B
UNION
SELECT A.FILEKEY, A.STATUS2 AS STATUS, A.EFFDATE2 AS EFFDATE FROM TABLEA A) C
WHERE C.EFFDATE <= '5/1/2011')
ORDER BY C.EFFDATE DESC