SQL查询帮助必需

时间:2012-02-04 09:06:02

标签: sql sql-server-2005

我有以下查询来获取前45天的数据

SELECT evening + morning + calve_milk AS Total_Today, 
       CONVERT (VARCHAR(6), m_date, 6) AS Date 
FROM Status 
WHERE (m_date < (SELECT MAX(m_date) AS Expr1 FROM Status AS Status_2))
   AND (m_date > (SELECT MAX(m_date) AS Expr1 FROM Status AS Status_1) - 45) 
   AND (animal_code = @animal_code) 
GROUP BY evening + morning + calve_milk, m_date 
ORDER BY m_date

当检索数据时,日期列看起来像这样

Jan 01
Jan 02
Jan 03
Jan 04
ans so on till the jan ends
Feb 01
Feb 02
Feb 03

我的问题是,这可能会跳过重复的JAN和FEB,每个日期和日期应该看起来像这样

Jan 01
    02
    03
    04
Feb 01
    02
    03

请任何人告诉我如何使用sql

3 个答案:

答案 0 :(得分:6)

可能,肯定,明智,可能不是。

您应该使用SQL获取数据并在前端应用程序中格式化数据(例如Reporting Services,Excel等)。

答案 1 :(得分:0)

以下是如何做到这一点。这是另一个表的一个例子。它创造了一切。你可以运行它,看看它是如何工作的:

DROP TABLE CURSOR_EXAMPLE
GO
CREATE TABLE CURSOR_EXAMPLE
(TEXT VARCHAR(8),VALUE BIGINT)
GO
INSERT INTO CURSOR_EXAMPLE
VALUES ('Jan',1)
INSERT INTO CURSOR_EXAMPLE
VALUES ('Jan',2)
INSERT INTO CURSOR_EXAMPLE
VALUES ('Feb',1)
INSERT INTO CURSOR_EXAMPLE
VALUES ('Feb',2)
INSERT INTO CURSOR_EXAMPLE
VALUES ('Mar',1)
INSERT INTO CURSOR_EXAMPLE
VALUES ('Mar',2)
INSERT INTO CURSOR_EXAMPLE
VALUES ('Apr',1)
INSERT INTO CURSOR_EXAMPLE
VALUES ('Apr',2)
GO

DECLARE @var_Current_TEXT VARCHAR(8);
DECLARE @text VARCHAR(8);
DECLARE @value BIGINT;

CREATE TABLE #TempResult
(TEXT VARCHAR(8),VALUE BIGINT)


DECLARE cu_CURSOR_EXAMPLE CURSOR FOR  
SELECT 
    TEXT
    ,VALUE
FROM CURSOR_EXAMPLE

OPEN cu_CURSOR_EXAMPLE  
FETCH NEXT FROM cu_CURSOR_EXAMPLE INTO @text, @value 

SET @var_Current_TEXT = ''
WHILE @@FETCH_STATUS = 0  
BEGIN  
    IF (@var_Current_TEXT <> @text)
        INSERT INTO #TempResult
        VALUES (@text, @value); 
    IF  (@var_Current_TEXT = @text)
        INSERT INTO #TempResult
        VALUES ('', @value); 

   SET @var_Current_TEXT = @text
   FETCH NEXT FROM cu_CURSOR_EXAMPLE INTO @text, @value
END 
CLOSE cu_CURSOR_EXAMPLE  
DEALLOCATE cu_CURSOR_EXAMPLE

SELECT * FROM  #TempResult

DROP TABLE #TempResult

答案 2 :(得分:0)

with CTE AS (
select mnth
,stats
,row_number() over(partition by mnth order by mnth) rn
from you_Table
)
select case when rn>1 THEN '' Else mnth END, stats
FROM CTE