让日期范围从2014年1月10日到2014年10月31日,数据在下面引用
记得我希望在sql
中开始和结束10月份的余额+------------+-----------+----------+---------+
| actualdate | linecost | balance | lineid |
+------------+-----------+----------+---------+
| 1/10/2014 | 100 | 250 | 73 |
| 14/10/2014 | 50 | 350 | 74 |
| 15/10/2014 | 200 | 450 | 75 |
| 18/10/2014 | 300 | 550 | 76 |
+------------+-----------+----------+---------+
输出应该是这样的!
月份起始余额结束余额
答案 0 :(得分:1)
使用GROUP BY
和DATENAME()
。
SELECT DATENAME(mm,actualDate) AS [Month],
MIN(balance) AS startingbalance,
MAX(balance) AS endingbalance
FROM tbl
GROUP BY DATENAME(mm,actualDate);
答案 1 :(得分:0)
尝试这样的事情: -
SELECT DATENAME(MONTH(ACTUAL_DATE)), MIN(BALANCE), MAX(BALANCE)
FROM TABLE_NAME
GROUP BY MONTH(ACTUAL_DATE)
这对你有用。
答案 2 :(得分:0)
MS SQL Server 2008架构设置:
CREATE TABLE tbl(actualDate DATETIME,lineCost INT,balance INT,lineid INT);
INSERT INTO tbl VALUES('2014-10-01 01:02:03',10,10,73);
INSERT INTO tbl VALUES('2014-10-14 01:03:10',10,20,74);
INSERT INTO tbl VALUES('2014-10-15 01:04:20',5,5,75);
INSERT INTO tbl VALUES('2014-10-18 01:05:30',3,1,76);
INSERT INTO tbl VALUES('2014-10-18 01:06:20',4,2,77);
INSERT INTO tbl VALUES('2014-10-18 01:07:10',6,100,78);
INSERT INTO tbl VALUES('2014-10-18 02:08:00',7,200,79);
INSERT INTO tbl VALUES('2014-10-18 03:09:50',8,150,80);
INSERT INTO tbl VALUES('2014-10-19 04:01:50',9,160,81);
INSERT INTO tbl VALUES('2014-10-20 05:09:50',11,170,82);
INSERT INTO tbl VALUES('2014-10-20 06:09:50',12,180,83);
INSERT INTO tbl VALUES('2014-10-20 07:29:40',50,380,84);
查询1 :
SELECT DATENAME(mm,actualDate) AS [Month],DATENAME(yyyy,actualDate) AS [YEAR],
(SELECT balance FROM tbl WHERE actualDate=(SELECT MIN(actualDate) FROM tbl)) AS startingbalance,
(SELECT balance FROM tbl WHERE actualDate=(SELECT MAX(actualDate) FROM tbl)) AS endingbalance
FROM tbl
GROUP BY DATENAME(mm,actualDate),DATENAME(yyyy,actualDate)
<强> [结果] [2] 强>:
| MONTH | YEAR | STARTINGBALANCE | ENDINGBALANCE |
|---------|------|-----------------|---------------|
| October | 2014 | 10 | 380 |