我有以下数据表:
CLIENT ART MONTH1 MONTH2 MONTH3
11 1 100 150 300
11 2 200 250 350
但我需要这个
CLIENT ART MONTH1 MONTH2 MONTH3 ART2 MONTH1_2 MONTH2_2 MONTH3_2
11 1 100 150 300 2 200 250 350
我试过这个SQL代码
SELECT cliente, [1] art1, SUM([10]) month1 , SUM([11]) month2, SUM([12]) month3, [10] art2 , SUM([10]) month1_2 , SUM([11]) month2_2, SUM([12]) month3_2
FROM (
SELECT v.cliente, MONTH(v.fechaemision) Mes, vd.articulo, vd.cantidad
FROM venta v
JOIN ventad vd on v.id=vd.id and v.mov='Estadistica'
) AS SourceTable
PIVOT(
max(articulo)
FOR articulo IN ( [100],[1])-- and Artiulo in ([100])
) AS PivotTable
PIVOT(
AVG(cantidad)
FOR Mes IN ( [10],[11],[12])-- and Artiulo in ([100])
) AS PivotTable
GROUP BY cliente, [10], [1]
结果如下;
CLIENT ART MONTH1 MONTH2 MONTH3 ART2 MONTH1_2 MONTH2_2 MONTH3_2
11 1 100 150 300 2 100 150 300
我可以推动艺术,但不是每个月第二艺术的数量。
任何人都可以指导我完成我想要的错误吗?
答案 0 :(得分:0)
考虑使用self-join tables,过滤ART
值比原始表少一个。为ART
CLIENT
项添加新的自联接表
SELECT v1.CLIENT, v1.ART, v1.MONTH1, v1.MONTH2, v1.MONTH3,
v2.ART As ART_2, v2.MONTH1 As MONTH1_2, v2.MONTH2 As MONTH2_2,
v2.MONTH3 As MONTH3_2
FROM ventad AS v1
INNER JOIN ventad As v2
ON v1.CLIENT = v2.CLIENT
WHERE v1.ART = v2.ART - 1
ORDER BY v1.CLIENT, v1.ART;