简体   繁体   English

选择每月的最后一天

[英]select last day of each month

I´m trying to work out this select but not getting anywhere-. 我正在尝试选择这个选项,但没有成功。 Please help. 请帮忙。 many thanks, Louise 非常感谢,路易斯


I need to get the sum of sales for the last date of each month group by custom and by month(fecha) 我需要通过自定义和按月(fecha)获取每个月组的最后日期的销售总额

for example, for custom ='q' in month=8 I have 3 items in the last day of the month ='2014-08-15' totalling 13 and so on 例如,对于在month = 8中的custom ='q',我在当月的最后一天有3个项目='2014-08-15',共13个,依此类推


DECLARE @sales TABLE
(custom VARCHAR(10) NOT NULL,
fecha DATE NOT NULL,
sales NUMERIC(10, 2) NOT NULL);

INSERT INTO @sales(custom, fecha, sales)
VALUES ('q', '20140708', 51),
('q', '20140712', 3), 
('q', '20140712', 3), 
('q', '20140712', 4), 
('q', '20140811', 3), 
('q', '20140812', 1),
('q', '20140815', 5),
('q', '20140815', 6),
('q', '20140815', 2),
('q', '20140114', 7),
('q', '20140714', 24),
('q', '20140714', 24),
('x', '20140709', 25),
('x', '20140710', 16),
('x', '20140711', 36),
('x', '20140712', 23),
('x', '20140712', 35),
('x', '20140715', 57),
('c', '20140712', 97),
('c', '20140715', 71);

Try this. 尝试这个。 Used CTE for better code readability 使用过的CTE以提高代码可读性

;WITH cte
     AS (SELECT custom, Max(fecha) fecha
         FROM   @sales
         GROUP  BY custom, Datepart(yyyy, fecha), Datepart(mm, fecha))
SELECT b.custom, b.fecha, Sum(b.sales) [Sum]
FROM   cte a
       JOIN @sales b
         ON a.custom = b.custom
            AND a.fecha = b.fecha
GROUP  BY b.custom, b.fecha 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM