简体   繁体   English

SQL-使用where子句的select中具有不同的总和级别

[英]SQL - Different sum levels in one select with where clause

I have 2 tables. 我有2张桌子。 One has the orginal amount that remains static. 一个人的原始数量保持不变。 The second table has a list of partial amounts applied over time against the orginal amount in the first table. 第二张表列出了随时间推移应用到第一张表中原始量的部分量的列表。

DB Tables: 数据库表:

***memotable***
ID [primary, unique]
Amount (Orginal Amount)

***transtable***
ID [many IDs in transtable to single ID in memotable] 
AmountUsed (amount applied)
ApplyDate (date applied)

I would like to find, in a single select, the ID, amount used since last week (ApplyDate > 2011-04-21), amount used to date. 我想一次找到ID,自上周以来使用的金额(ApplyDate> 2011-04-21),迄今使用的金额。

The only rows that should appear in the result is when an amount has been used since last week (ApplyDate > 2011-04-21). 结果应显示的唯一行是自上周以来已使用金额的时间(ApplyDate> 2011-04-21)。

I'm stuck on trying to get the sum for the amount used to date, since that needs to include AmountUsed values that are outside of when ApplyDate > 2011-04-21. 我一直试图获取迄今为止使用金额的总和,因为这需要包括ApplyDate> 2011-04-21之外的AmountUsed值。

It is possible to avoid subselects in this case: 在这种情况下,可以避免子选择:

SELECT
  ID,
  AmountUsedSinceLastWeek = SUM(CASE WHEN ApplyDate > '4/21/2011' THEN AmountUsed END)
  AmountUsedToDate = SUM(AmountUsed)
FROM TransTable
GROUP BY ID

Since you want to limit it to rows that happened since last week, but also want to include the total to date, I think the most efficient method would be to use sub-selects... 由于您希望将其限制为上周以来发生的行,而且还希望包括迄今为止的总数,因此我认为最有效的方法是使用子选择...

SELECT
    lastWeek.ID,
    lastWeek.AmountUsedSinceLastWeek,
    toDate.AmountUsedToDate
FROM
(
    SELECT
        ID,
        SUM(AmountUsed) AS AmountUsedSinceLastWeek
    FROM TransTable
    WHERE ApplyDate > '4/21/2011'
    GROUP BY ID
) lastWeek JOIN
(
    SELECT
        ID,
        SUM(AmountUsed) AS AmountUsedToDate
    FROM TransTable
    GROUP BY ID
) toDate ON lastWeek.ID = toDate.ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM