sql - 毫秒访问查询枢轴
问题描述
我有两张桌子。
tblA
ID Date Price
--------------------
1 10/1/18 100
2 10/2/18 200
3 10/1/19 50
tblB
ID Date Price
------------------
1 10/5/18 100
2 10/6/18 100
3 10/7/18 100
我有以下查询来总结每月的价格。
TRANSFORM IIf(Sum([SumPrice]) Is Null,0,Sum([SumPrice])) AS PricePerMonth
SELECT Format([AllDate],"yyyy") AS [Year], t.Name
FROM (
SELECT [Date] as AllDate, Nz(Price, 0) AS SumPrice, 'tblA' As Name
FROM tblA
UNION All
SELECT [Date] as AllDate, Nz(Price, 0) AS SumPrice, 'tblB' As Name
FROM tblB
) AS t
GROUP BY Format([AllDate],"yyyy"), t.Name
ORDER BY Format([AllDate],"yyyy") DESC , t.Name
PIVOT Month([AllDate]) In (1,2,3,4,5,6,7,8,9,10,11,12);
输出查询:
Year Name 1 2 3 4 5 6 7 8 9 10 11 12
--------------------------------------------------------------------------
2019 tblA 50 0 0 0 0 0 0 0 0 0 0 0
2018 tblA 100 200 0 0 0 0 0 0 0 0 0 0
2018 tblB 0 0 0 0 100 100 100 0 0 0 0 0
有没有办法得到这个输出:
Year Name 1 2 3 4 5 6 7 8 9 10 11 12
--------------------------------------------------------------------------
2019 tblA 50 0 0 0 0 0 0 0 0 0 0 0
2019 tblB 0 0 0 0 0 0 0 0 0 0 0 0 <===Different from above.
2018 tblA 100 200 0 0 0 0 0 0 0 0 0 0
2018 tblB 0 0 0 0 100 100 100 0 0 0 0 0
如您所见,tblB 没有 2019 年的数据。所以我需要想办法添加它。
谢谢你。
解决方案
在 Union All 中添加了额外的 Select 以获取另一个表中缺少的日期。
TRANSFORM IIf(Sum([SumPrice]) Is Null,0,Sum([SumPrice])) AS PricePerMonth
SELECT Format([AllDate],"yyyy") AS [Year], t.Name
FROM (
SELECT [Date] as AllDate, Nz(Price, 0) AS SumPrice, 'tblA' As Name
FROM tblA
UNION All
SELECT [Date] as AllDate, Nz(Price, 0) AS SumPrice, 'tblB' As Name
FROM tblB
Union All
SELECT tblb.Date as dt, 0 , 'tblA' As Name
FROM tblB Left JOIN tblA ON Format(tblA.[Date],'yyyy') = Format(tblB.[Date],'yyyy')
where not Format(tblA.Date,'yyyy') = Format(tblb.Date,'yyyy')
Union All
SELECT (tblA.Date) as dt, 0 , 'tblB' As Name
FROM tblA Left JOIN tblB ON Format(tblA.[Date],'yyyy') = Format(tblB.[Date],'yyyy')
where not Format(tblA.Date,'yyyy') = Format(tblb.Date,'yyyy')
) AS t
GROUP BY t.Name,Format([AllDate],"yyyy")
ORDER BY Format([AllDate],"yyyy") DESC , t.Name
PIVOT Month([AllDate]) In (1,2,3,4,5,6,7,8,9,10,11,12)
推荐阅读
- text - 替换大 txt 文件上的文本函数值输入不起作用
- python - python最后一个数字重复不止一次
- tabulator - 如何在制表器中通过 ajax 加载列
- laravel - Laravel + Xtext DSL | 在 Laravel 中使用 DSL
- c++ - 如何在 C++ 中读取两位数和一位数
- c++ - 带有 clang 格式选项 AlwaysBreakAfterReturnType 和 AfterFunction 的奇怪结果
- vba - 解析和格式化文本文件
- python - 无法在 Django SQLlite 内存数据库中应用迁移
- powershell - 使用 windows powershell 批量重命名
- ios - 需要有关通过 UINavigationController 传递数据的技术建议