我有一张表@sales
,其中记录了销售额和利润
下面的选择为我提供了2个特定日期的销售和利润摘要
挑战如下:
我需要将其替换为:
,而不是对日期进行硬编码所以在下面的示例中将是:
是否可以使用columna_1_p / columna_1添加其他列?
任何人都可以帮忙吗?
DECLARE @sales TABLE
(
custom VARCHAR(10) NOT NULL,
fecha_valor DATE NOT NULL,
sales NUMERIC(10, 2) NOT NULL,
profits NUMERIC(10, 2) NOT NULL
);
INSERT INTO @sales(Custom, Fecha_valor, sales, profits)
VALUES ('q', '20140708', 51,21),
('q', '20140712', 3,33),
('q', '20140712', 5,12),
('q', '20140711', 6,43),
('q', '20140712', 2,66),
('q', '20140712', 7,21),
('q', '20140714', 24,76),
('q', '20140714', 24,12),
('x', '20140709', 25,0),
('x', '20140710', 16,0),
('x', '20140711', 66,31),
('x', '20140712', 23,12),
('x', '20140712', 35,11),
('x', '20140714', 57,1),
('c', '20140712', 97,2),
('c', '20140714', 71,3);
SELECT
custom,
CAST(SUM(Case fecha_valor when '2014-07-12' then sales ELSE 0 END) AS numeric(12, 3)) as columna_1,
CAST(SUM(Case fecha_valor when '2014-07-14' then sales ELSE 0 END) AS numeric(12, 3)) as columna_2,
CAST(SUM(Case fecha_valor when '2014-07-12' then profits ELSE 0 END) AS numeric(12, 3)) as columna_1_P,
CAST(SUM(Case fecha_valor when '2014-07-14' then profits ELSE 0 END) AS numeric(12, 3)) as columna_2_P
FROM
@sales
GROUP BY
custom;
答案 0 :(得分:0)
不确定您在最终结果中究竟在寻找什么,但是下面的内容会有所帮助吗?
SELECT Custom, Fecha_valor, sales, profits FROM sales ORDER BY Fecha_valor DESC LIMIT 2
答案 1 :(得分:0)
您可以使用以下查询:
DECLARE @FirstDate DATE,
@SecondDate DATE
SELECT @FirstDate = MAX(fecha_valor) FROM @Sales
SELECT @SecondDate = MAX(fecha_valor) FROM @Sales WHERE fecha_valor<> @FirstDate
SELECT custom,
CAST(SUM(Case fecha_valor when @SecondDate THEN sales ELSE 0 END) AS numeric(12, 3)) as columna_1,
CAST(SUM(Case fecha_valor when @FirstDate THEN sales ELSE 0 END) AS numeric(12, 3)) as columna_2,
CAST(SUM(Case fecha_valor when @SecondDate THEN profits ELSE 0 END) AS numeric(12, 3)) as columna_1_P,
CAST(SUM(Case fecha_valor when @FirstDate THEN profits ELSE 0 END) AS numeric(12, 3)) as columna_2_P
FROM @sales
GROUP BY custom;