返回每个普通组的最新日期

时间:2013-03-08 21:46:02

标签: sql sql-server-2008 sql-server-2005

使用SQL Server 2005/2008和此查询:

DECLARE @FromDate DATETIME, @Todate DATETIME

SET @FromDate = '1/1/2012'
SET @Todate = '1/1/2013'

SELECT
    CASE WHEN (GROUPING(s.storeid)=1) THEN 'Total' ELSE s.storeid END AS Store,
    CAST(SUM(p.amount) AS DECIMAL(12,2)) AS Paid,
    CAST((SELECT 
            TOP 1 s.TRSDate 
        FROM 
            RPTrs s, 
            rpPay p 
        WHERE 
            s.StoreID = p.StoreID AND 
            s.ReceiptNO = p.ReceiptNo 
        ORDER BY 
            s.TRSDate DESC) AS DATETIME) AS LastTransaction
FROM 
    rptrs s, rppay p
WHERE 
    s.ReceiptNO = p.ReceiptNo AND 
    s.StoreID = p.StoreID AND 
    s.TRSDate >= @FromDate AND 
    s.TRSDate <= @Todate
GROUP BY 
    s.StoreID
WITH ROLLUP

我得到了这个输出:

enter image description here

它为Store 01添加了正确的日期而不是Store 02,我希望Total line中没有任何内容。

预期结果:

  | Store | Paid     | LastTransaction
-----------------------------------------------
1 | 01    | 59490.05 | 2013-03-06 00:00:00.000
2 | 02    | 238.15   | 2012-12-03 00:00:00.000
3 | Total | 59728.20 |

情况。此查询返回每个商店的总金额和总金额。除此之外,我现在需要添加的是显示的商店中发生的最后一个事务。由于日期范围介于2012年1月1日至2013年1月1日之间,因此存储2中发生的最后一个事务是预期结果中的事务。商店1在另一个时间进行了最后一笔交易。

第一张桌子是RPTrs,第二张桌子是rpPay

enter image description here

问题 - 如何获得预期结果?

3 个答案:

答案 0 :(得分:0)

  

根据您提供的样本。试试这个。您需要根据您的要求和数据对其进行一些修改。

SELECT R.StoreID, 
       CAST(SUM(p.amount) AS DECIMAL(12,2)) AS Paid,
       MAX(TRSDate)
FROM RPTrs R
INNER JOIN rpPay p ON R.StoreID = P.StoreID
GROUP BY R.StoreID
  

SQL FIDDLE DEMO

答案 1 :(得分:0)

我能够解决问题的一半部分。

DECLARE @FromDate DATETIME, @Todate DATETIME

SET @FromDate = '1/1/2012'
SET @Todate = '1/1/2013'

SELECT
    CASE WHEN (GROUPING(s.storeid)=1) THEN 'Total' ELSE s.storeid END AS Store,
    CAST(SUM(p.amount) AS DECIMAL(12,2)) AS Paid,
    CASE WHEN (GROUPING(s.StoreID)=1) THEN null ELSE CAST(MAX(s.TRSDate) AS DATETIME) END AS LastTransaction
FROM 
    rptrs s, rppay p
WHERE 
    s.ReceiptNO = p.ReceiptNo AND 
    s.StoreID = p.StoreID AND 
    s.TRSDate >= @FromDate AND 
    s.TRSDate <= @Todate
GROUP BY 
    s.StoreID
WITH ROLLUP

给出了:

enter image description here

现在,如何将NULL DATETIME显示为空格?

答案 2 :(得分:0)

对我有用的最终答案:

DECLARE @FromDate DATETIME, @Todate DATETIME

SET @FromDate = '1/1/2012'
SET @Todate = '1/1/2013'

SELECT
    CASE WHEN (GROUPING(s.storeid)=1) THEN 'Total' ELSE s.storeid END AS Store,
    CAST(SUM(p.amount) AS DECIMAL(12,2)) AS Paid,
    ISNULL(CONVERT(VARCHAR(50),(CASE WHEN (GROUPING(s.StoreID)=1) THEN null ELSE CAST(MAX(s.TRSDate) AS DATETIME) END)), '')AS LastTransaction
FROM 
    rptrs s, rppay p
WHERE 
    s.ReceiptNO = p.ReceiptNo AND 
    s.StoreID = p.StoreID 
GROUP BY 
    s.StoreID
WITH ROLLUP