2

点击图片查看表结构和问题 http://i.stack.imgur.com/odWKL.png

在此处输入图像描述

SELECT B.ENTITYID, 
       B.BALANCEDATE,
       B.BALANCE, 
       MIN(DATEDIFF(DAY,B.BALANCEDATE,C.STATUSDATE)) RECENT
FROM   BALANCES B JOIN STATUS C ON B.ENTITYID = C.ENTITYID
GROUP  BY B.ENTITYID, B.BALANCEDATE,B.BALANCE
HAVING B.ENTITYID =1

我已经尝试了以下方法,但由于更多的嵌套选择在访问类似属性时存在问题,因此无法走得更远:

4

3 回答 3

4

如果您正在使用 SQL Server,请参阅@ljh 的答案。下面的解决方案适用于 MySQL。由于 MySQL 不支持CTEWindow Function.

MySQL

SET @entity_name = 'ABCD';

SELECT  b.*, d.Status
FROM    Entity a
        INNER JOIN Balances b
            ON a.EntityID = b.EntityID
        LEFT JOIN
        (
            SELECT  a.EntityID, 
                    a.StatusDate StartDate, 
                    b.StatusDate + Interval -1 DAY EndDate,
                    a.Status
            FROM
                    (
                        SELECT  b.*, @r1 := @r1 + 1 AS Row_number
                        FROM    `Entity` a
                                INNER JOIN Status b
                                    ON a.EntityID = b.EntityID
                                CROSS JOIN (SELECT @r1 := 0) rowCount
                        WHERE   a.EntityName = @entity_name
                        ORDER   BY b.Status ASC
                    ) a
                    LEFT JOIN
                    (
                        SELECT  b.*, @r2 := @r2 + 1 AS Row_number
                        FROM    `Entity` a
                                INNER JOIN Status b
                                    ON a.EntityID = b.EntityID
                                CROSS JOIN (SELECT @r2 := 1) rowCount
                        WHERE   a.EntityName = @entity_name
                        ORDER   BY b.Status ASC
                    ) b ON  a.Row_number = b.Row_number
        ) d 
        ON b.BalanceDate BETWEEN d.StartDate AND d.EndDate
WHERE   a.EntityName = @entity_name

简要分解

由于 MySQL 不支持Windowing FunctionROW_NUMBER(),因此下面的查询用于为每条记录User Variable提供类似的行号ROW_NUMBER(),然后将用于连接另一个子查询。

SELECT  b.*, @r1 := @r1 + 1 AS Row_number
FROM    `Entity` a
        INNER JOIN Status b
            ON a.EntityID = b.EntityID
        CROSS JOIN (SELECT @r1 := 0) rowCount
WHERE   a.EntityName = @entity_name
ORDER   BY b.Status ASC

输出

╔══════════╦═════════════════════════════════╦════════╦════════════╗
║ ENTITYID ║           STATUSDATE            ║ STATUS ║ ROW_NUMBER ║
╠══════════╬═════════════════════════════════╬════════╬════════════╣
║        1 ║ May, 29 2010 00:00:00+0000      ║ A      ║          1 ║
║        1 ║ April, 16 2010 00:00:00+0000    ║ B      ║          2 ║
║        1 ║ April, 02 2010 00:00:00+0000    ║ C      ║          3 ║
║        1 ║ February, 26 2010 00:00:00+0000 ║ D      ║          4 ║
╚══════════╩═════════════════════════════════╩════════╩════════════╝

为记录提供行号的主要目的是将其用于连接另一个子查询,以便我们可以得到StartDateand EndDatefor each Status。这很容易,SQL Server 2012因为它有一个名为LAG()的窗口函数

╔══════════╦═════════════════════════════════╦══════════════════════════════╦════════╗
║ ENTITYID ║            STARTDATE            ║           ENDDATE            ║ STATUS ║
╠══════════╬═════════════════════════════════╬══════════════════════════════╬════════╣
║        1 ║ May, 29 2010 00:00:00+0000      ║ (null)                       ║ A      ║
║        1 ║ April, 16 2010 00:00:00+0000    ║ May, 28 2010 00:00:00+0000   ║ B      ║
║        1 ║ April, 02 2010 00:00:00+0000    ║ April, 15 2010 00:00:00+0000 ║ C      ║
║        1 ║ February, 26 2010 00:00:00+0000 ║ April, 01 2010 00:00:00+0000 ║ D      ║
╚══════════╩═════════════════════════════════╩══════════════════════════════╩════════╝

一旦组织好状态范围。它现在是每个Balances.

最终结果

╔══════════╦═════════════════════════════════╦═════════╦════════╗
║ ENTITYID ║           BALANCEDATE           ║ BALANCE ║ STATUS ║
╠══════════╬═════════════════════════════════╬═════════╬════════╣
║        1 ║ May, 01 2010 00:00:00+0000      ║     100 ║ B      ║
║        1 ║ April, 01 2010 00:00:00+0000    ║      50 ║ D      ║
║        1 ║ March, 01 2010 00:00:00+0000    ║      75 ║ D      ║
║        1 ║ February, 01 2010 00:00:00+0000 ║      85 ║ (null) ║
╚══════════╩═════════════════════════════════╩═════════╩════════╝

SQL Server 2012

上面演示的查询MySQL可以TSQL通过使用Common Table ExpressionWindow Function使用LAG() 轻松转换(仅在 SQL Server 2012 中引入

WITH lookupTable
AS
(
    SELECT  EntityID, 
            StatusDate StartDate, 
            DATEADD(DAY, -1, LAG(StatusDate) OVER(PARTITION BY EntityID ORDER BY Status)) EndDate,
            Status
    FROM    Status
)
SELECT  b.*, d.Status
FROM    Entity a
        INNER JOIN Balances b
            ON a.EntityID = b.EntityID
        LEFT JOIN lookupTable d
            ON b.BalanceDate BETWEEN d.StartDate AND d.EndDate AND
               d.EntityID = a.EntityID
WHERE   a.EntityName = 'ABCD'

输出

╔══════════╦═════════════════════════════════╦═════════╦════════╗
║ ENTITYID ║           BALANCEDATE           ║ BALANCE ║ STATUS ║
╠══════════╬═════════════════════════════════╬═════════╬════════╣
║        1 ║ May, 01 2010 00:00:00+0000      ║     100 ║ B      ║
║        1 ║ April, 01 2010 00:00:00+0000    ║      50 ║ D      ║
║        1 ║ March, 01 2010 00:00:00+0000    ║      75 ║ D      ║
║        1 ║ February, 01 2010 00:00:00+0000 ║      85 ║ (null) ║
╚══════════╩═════════════════════════════════╩═════════╩════════╝
于 2013-03-30T08:28:39.057 回答
2

以 SQL Server 2012 作为 RDBMS 为例。这是您需要的第一个查询。
这个答案使用了 SQL CTE(通用表表达式),它可能不适用于其他 RDBMS 系统。
SQL FIDDLE DEMO
查询说明:
1. 先连接[Balances] 和[Status] 表,使用BalanceDate > StatusDate 过滤结果,返回两个表的所有列,这是因为后面需要。
2.将步骤.1的输出与[Entity]表连接,使用EntityName过滤结果,仍然保留3个表中的所有列,当然不需要重复的EntityID。
3. 使用 CTE 保存连接
4. 使用 CTE 保存应用在连接输出上的排名
5. 使用 Rank number 过滤掉结果和按 BalanceDate 排序


;with CTE_AfterJoin
as 
(
    select E.EntityID, E.EnityName, C.BalanceDate, C.Balance, C.StatusDate, C.status
    from Entity E
    left join (
            select B.EntityID, B.BalanceDate, B.Balance,S.StatusDate, S.[Status]
            from Balances B 
            left join  [Status] S
            on B.EntityID = S.EntityID and B.BalanceDate > S.StatusDate
            ) C
    on E.EntityID = C.EntityID
    where E.EnityName = 'ABCD'
),
CTE_afterRank
as 
(
    select EnityName, BalanceDate, Balance, 
           rank() over (partition by BalanceDate order by StatusDate desc) as Rn, Status 
    from CTE_AfterJoin
)
select EnityName, BalanceDate, Balance, Status
from CTE_afterRank
where Rn = 1
order by BalanceDate desc
于 2013-03-30T08:17:02.530 回答
1

同样在 SQLServer2005+ 中,您可以将选项与APPLY()运算符一起使用。

APPLY 运算符允许您连接两个表表达式。每次对左表表达式中的每一行处理右表表达式。最终结果集包含从左表表达式中选择的所有列,然后是右表表达式的所有列。OUTER APLLY 对于右表表达式中没有对应匹配的那些行,它在右表表达式的列中包含 NULL 值。

SELECT e.EntityName, b.BalanceDate AS Date, b.Balance, o.Status
FROM Entity e JOIN Balances b ON e.EntityID = b.EntityID
              OUTER APPLY (
                           SELECT TOP 1 s.Status AS Status                           
                           FROM Status s
                           WHERE b.EntityID = s.EntityID 
                             AND s.StatusDate < b.BalanceDate
                           ORDER BY s.StatusDate DESC
                           ) o
WHERE e.EntityName = 'ABCD' 

为了提高性能(强制 INDEX SEEK 操作)将此索引与 INCLUDE 子句一起使用。INCLUDE 子句在最低/叶级别添加数据,而不是在索引树中。这使得索引更小,因为它不是树的一部分

CREATE INDEX x ON Status(StatusDate) INCLUDE(EntityID, Status)
CREATE INDEX x ON Entity(EntityName) INCLUDE(EntityID)
CREATE INDEX x ON Balances(EntityID, BalanceDate, Balance)

SQLFiddle上的演示

在此处输入图像描述

于 2013-03-30T09:32:48.633 回答