我有一张这样的表:
id Date Qty
1 Feb 25 2015 12:00AM 34
2 Feb 27 2015 12:00AM 34
3 Mar 17 2015 12:00AM 153
4 Mar 27 2015 12:00AM 68
5 Apr 3 2015 12:00AM 153
6 May 6 2015 12:00AM 153
我想选择第一个日期,我将有足够的数量来满足我的需要。 我提出的这个请求适用于大多数情况,但是当我需要210时,不会对这些数据有效。它应该选择我MAR 17,但我有2月27日
SELECT top 1
T1.Date,
T1.Qty
,SUM(cast (T2.Qty as int)) AS cumulqte
FROM
##temptest3 T1
INNER JOIN ##temptest3 T2
ON T1.Date >= T2.Date
GROUP BY T1.id, T1.Date, T1.Qty
HAVING SUM(cast (T2.Qty as int)) >=210
ORDER BY T1.Date;
我试图改变顺序和很多东西,但没有任何效果。
编辑: 这是我创建表格的方式:
select * into ##temptest1 from sysadm.fnSplitString('17223ü17225ü17243ü17253ü17260ü17293','ü')
update ##temptest1 set splitdata=DATEADD(day,cast(splitdata as int), '1967-12-31');
select * into ##temptest2 from sysadm.fnSplitString('34ü34ü153ü68ü153ü153','ü')
update ##temptest2 set splitdata='0' where splitdata=''
create table ##temptest3 (id int,Date nvarchar(max), Qte NVARCHAR(MAX) )
INSERT INTO ##temptest3 (id, Qte, Date) select ##temptest2.id, ##temptest2.splitdata, ##temptest1.splitdata from ##temptest2 inner join ##temptest1 on ##temptest2.id=##temptest1.id
答案 0 :(得分:1)
正如我在评论中所说,您需要将日期字段转换/转换为日期或日期时间,以使订单正常工作:
SELECT top 1
T1.Date,
T1.Qty
,SUM(cast (T2.Qty as int)) AS cumulqte
FROM
##temptest3 T1
INNER JOIN ##temptest3 T2
ON T1.Date >= T2.Date
GROUP BY T1.id, T1.Date, T1.Qty
HAVING SUM(cast (T2.Qty as int)) >=210
ORDER BY Cast(T1.Date as datetime)
答案 1 :(得分:1)
问题在于,当您创建##临时表时,您使用nvarchar
类型而不是datetime
(以及int
来表示qty)。最好的补救方法是在创建表时使用正确的类型,如果不能工作,您可以在查询中使用强制转换,如下所示:
SELECT top 1
cast(t1.Date as datetime),
T1.Qty
,SUM(cast (T2.Qty as int)) AS cumulqte
FROM
##temptest3 T1
INNER JOIN ##temptest3 T2
ON cast(t1.Date as datetime) >= cast(t2.Date as datetime)
GROUP BY T1.id, cast(t1.Date as datetime), T1.Qty
HAVING SUM(cast (T2.Qty as int)) >=210
ORDER BY cast(t1.Date as datetime);
请参阅此SQL Fiddle
答案 2 :(得分:0)
试试这个:
DECLARE @TEMP_COMMUNICATION_TABLE TABLE (ID INT IDENTITY(1,1), [DATE] DATETIME, QTY INT)
INSERT INTO @TEMP_COMMUNICATION_TABLE VALUES ('2015-02-27',34),('2015-02-25',34),('2015-03-17',153),('2015-03-27',68),('2015-04-03',153),('2015-05-06',153)
--SELECT * FROM @TEMP_COMMUNICATION_TABLE
DECLARE @INPUT INT = 210
SELECT TOP 1
T1.Date,
T1.Qty,
SUM(T2.QTY)
FROM @TEMP_COMMUNICATION_TABLE T1
INNER JOIN @TEMP_COMMUNICATION_TABLE T2
ON T1.DATE >= T2.DATE
GROUP BY
T1.Date,
T1.Qty
HAVING SUM(cast (T2.Qty as int)) >=@INPUT
--ORDER BY T1.Date;
您的查询非常完美,请按顺序删除。