2011-06-06 171 views
0

我有一個查詢從1分鐘到任何其他時間框架聚合(壓縮)數據,它完美的作品。修改查詢sql

Use StockDataFromSella; 
DECLARE @D1 DateTime 
DECLARE @D2 DateTime 
DECLARE @Interval FLOAT 

SET @D1 = '2008-09-21T09:00:00.000' 
SET @D2 = '2010-10-20T17:30:00.000' 
SET @Interval = 15 

;WITH 
L0 AS (SELECT 1 AS c UNION ALL SELECT 1), 
L1 AS (SELECT 1 AS c FROM L0 A CROSS JOIN L0 B), 
L2 AS (SELECT 1 AS c FROM L1 A CROSS JOIN L1 B), 
L3 AS (SELECT 1 AS c FROM L2 A CROSS JOIN L2 B), 
L4 AS (SELECT 1 AS c FROM L3 A CROSS JOIN L3 B), 
Nums AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS i FROM L4), 
Ranges AS( 
SELECT 
     DATEADD(MINUTE,@Interval*(i-1),@D1) AS StartRange, 
     DATEADD(MINUTE,@Interval*i,@D1) AS NextRange 
FROM Nums where i <= 1+CEILING(DATEDIFF(MINUTE,@D1,@D2)/@Interval)) 
,cte AS ( 
SELECT 
    * 
    ,ROW_NUMBER() OVER (PARTITION BY Simbolo,r.StartRange ORDER BY [DataOra])  AS RN_ASC 
    ,ROW_NUMBER() OVER (PARTITION BY Simbolo,r.StartRange ORDER BY [DataOra] DESC) AS RN_DESC 
FROM Ranges r 
JOIN dbo.tbl1MinENI p ON p.[DataOra] >= r.StartRange and p.[DataOra] < r.NextRange) 
SELECT 
     Simbolo, 
     MAX(CASE WHEN RN_ASC=1 THEN [DataOra] END) AS DataOra, 
     MAX(CASE WHEN RN_ASC=1 THEN [Apertura] END) AS [Apertura], 
     MAX(Massimo) Massimo, 
     MIN(Minimo) Minimo, 
     MAX(CASE WHEN RN_DESC=1 THEN [Chiusura] END) AS [Chiusura], 
     SUM(Volume) Volume 
     /*MAX(CASE WHEN RN_DESC=1 THEN [DataOra] END) AS ChiusuraDataOra*/ 
FROM cte 
GROUP BY Simbolo,StartRange 
ORDER BY DataOra 

我想第二列DataOra(日期時間)分割成兩個diferent列,一個用於日期(如果不可能性在DD/MM/yyyy格式)和第二對只有時間。 任何幫助非常感謝,謝謝。 Alberto

+0

您使用的是哪個**版本**(2005,2008,2008 R2)? – 2011-06-06 20:59:34

+0

Microsoft SQL Server Management Studio Express(SQL Server 2005) – 2011-06-06 21:01:50

回答

2

獲取這些值的最簡單方法是使用CONVERT。轉換日期時,SQL Server有一些內置的日期格式。

CONVERT(VARCHAR, MAX(CASE WHEN RN_ASC=1 THEN [DataOra] END), 103) AS DataOraDate, 
CONVERT(VARCHAR, MAX(CASE WHEN RN_ASC=1 THEN [DataOra] END), 114) AS DataOraTime, 

這兩個代碼(103和114)對應於您想要的格式。請參閱http://msdn.microsoft.com/en-us/library/ms187928.aspx瞭解有關這些以及可以轉換爲的其他格式的更多詳細信息。

+0

@dpmattingly我以爲像你一樣,但我認爲它不會工作,因爲選擇不會做整個日期時間的最大值,它會做最大隻是在一列中比較沒有時間的日期,在另一個日期中只與時間比較並且不比較日期。 – 2011-06-06 21:10:00

+1

你是對的,你需要將CONVERT帶到MAX以外才能使其工作。我已經調整了它以減少混淆,但我認爲它與您的答案相同。 – dpmattingly 2011-06-06 21:17:37

+0

謝謝,它的工作原理,我有兩個日期和時間分割列:我認爲日期必須有比103更好的東西。我設置了ORDER BY DataOraDate,並且我有第1天,然後從1到12的月份,第2天,從1到12的月份等等。我應該有1到30(31)與第1個月的一天,等等。感謝 – 2011-06-06 21:26:00

2

看來你只需要改變選擇。 而是這個

MAX(CASE WHEN RN_ASC=1 THEN [DataOra] END) AS DataOra, 

使用此的:

CONVERT(VARCHAR(8),MAX(CASE WHEN RN_ASC=1 THEN [DataOra] END),108) AS HourMinuteSecond, 
CONVERT(VARCHAR(8),MAX(CASE WHEN RN_ASC=1 THEN [DataOra] END),101) AS DateOnly, 

希望它能幫助。