我有一个有两列的表。
pydt Decimal(13,0) and amt Decimal(18,4)
payDt列包含UNIX时间戳中的日期时间,而amt包含金额。 现在我需要明智地报告一周。为此我使用bellow命令。
Select X.PMonth,X.PWeek,SUM(X.Payment) as Payment from
(
select
MONTH(dateadd(s,CAST(LEFT(pydt, LEN(pydt) - 3) AS DECIMAL(10,0)),'01/01/1970')) as PMonth,
DATEPART(WK,dateadd(s,CAST(LEFT(pydt, LEN(pydt) - 3) AS DECIMAL(10,0)),'01/01/1970')) as PWeek,
amt as Payment
from tblpayment
)X
group by
X.PMonth,X.PWeek
order by X.PMonth,X.PWeek
它有效。 现在我需要指定周开始和周以及报告。 意味着我需要一个SQL查询,它根据给定的周开始日和周末日自动对数据求和。
Mon to Sun,Tue to Mon,........... and Sun to Mon
任何人都可以告诉我该怎么做。
DECLARE @TESTTABLE TABLE(pydt DECIMAL(13,0),amt DECIMAL(18,4))
INSERT INTO @TESTTABLE
SELECT 1371633942104, 500.000 UNION ALL
SELECT 1371536351014, 200.000 UNION ALL
SELECT 1371508936993, 800.000 UNION ALL
SELECT 1371421684905, 800.000 UNION ALL
SELECT 1371279960886, 500.000 UNION ALL
SELECT 1371250768515, 900.000 UNION ALL
SELECT 1371115833490, 200.000 UNION ALL
SELECT 1371052445207, 100.000 UNION ALL
SELECT 1370935778269, 100.000 UNION ALL
SELECT 1370874220086, 200.000 UNION ALL
SELECT 1370790602634, 100.000 UNION ALL
SELECT 1370679256936, 300.000 UNION ALL
SELECT 1370644477888, 100.000 UNION ALL
SELECT 1370524059728, 500.000 UNION ALL
SELECT 1370419275541, 100.000 UNION ALL
SELECT 1370383832831, 900.000 UNION ALL
SELECT 1370299308283, 100.000 UNION ALL
SELECT 1370211913979, 200.000 UNION ALL
SELECT 1370066810107, 100.000 UNION ALL
SELECT 1370039853256, 200.000 UNION ALL
SELECT 1369888990306, 200.000 UNION ALL
SELECT 1369864999229, 1000.000 UNION ALL
SELECT 1369863700412, 200.000 UNION ALL
SELECT 1369863257127, 300.000 UNION ALL
SELECT 1369863225725, 200.000 UNION ALL
SELECT 1369860049462, 100.000 UNION ALL
SELECT 1369859952006, -47.640 UNION ALL
SELECT 1369858718486, 100.000 UNION ALL
SELECT 1369835887771, 100.000 UNION ALL
SELECT 1369815058443, 100.000 UNION ALL
SELECT 1369781776403, 900.000
Select min(X.pydt) as [Start From],max(X.pydt) as [End To],MAX(X.PMonth) AS PMonth,X.PWeek,SUM(X.Payment) as Payment from
(
select
dateadd(s,CAST(LEFT(pydt, LEN(pydt) - 3) AS DECIMAL(10,0)),'01/01/1970') as pydt,
MONTH(dateadd(s,CAST(LEFT(pydt, LEN(pydt) - 3) AS DECIMAL(10,0)),'01/01/1970')) as PMonth,
DATEPART(WK,dateadd(s,CAST(LEFT(pydt, LEN(pydt) - 3) AS DECIMAL(10,0)),'01/01/1970')) as PWeek,
amt as Payment
from @TESTTABLE
)X
group by
X.PWeek
order by PMonth,X.PWeek
Start From End To PMonth PWeek Payment
2013-05-28 22:56:16 2013-06-01 06:06:50 6 22 3452.3600
2013-06-02 22:25:13 2013-06-08 08:14:16 6 23 2200.0000
2013-06-09 15:10:02 2013-06-15 07:06:00 6 24 2100.0000
2013-06-16 22:28:04 2013-06-19 09:25:42 6 25 2300.0000
此处的结果显示周日至周六的分组数据。 现在我需要按照特定日期的数据进行分组。
From 2013-06-02 22:25:13(Sunday) To 2013-06-08 08:14:16(Saturday)
From 2013-06-04 22:25:13(Tuesday) To 2013-06-08 08:14:16(Monday)
我认为每件事都很清楚。
答案 0 :(得分:0)
如果我正确理解您的问题,您可以在代码的开头
执行此操作set datefirst 2
这将使星期二成为你一周的第一天。这也将使星期一成为你一周的最后一天。