我的T-SQL查询需要帮助。我想要做的是以下几点:
在结果中,我希望在第二列中按Store no.
分组的一列我希望net Amount
的总和为Sales
,而我希望它的第三列显示去年的销售额对于每个store no.
+-------+--------+------------+
| Store | Sales | Last Year |
+-------+--------+------------+
| 401 | 20000 | 19000 |
| 402 | 25000 | 21000 |
| 403 | 10000 | 15000 |
+-------+--------+------------+
注意:今年的销售额位于一个名为" Trans_ Sales Entry"并且去年的销售额存档在名为" Archived Sales Entry"
的表格中我也不想在查询中手动输入日期,我宁愿想要一个变量例如("今天"和"今天" -365)
这是正确的方法,还是有更好的方法?
SELECT
"Company$Trans_ Sales Entry"."Store No_" AS "Store",
SUM("Company$Trans_ Sales Entry"."Net Amount"*-1) AS "Sales",
SUM("Company$Archived Sales Entry"."Net Amount"*-1) AS "Last Year"
FROM "Company$Trans_ Sales Entry"
JOIN "Company$Archived Sales Entry" ON
"Company$Trans_ Sales Entry"."Store No_"="Company$Archived Sales Entry"."Store No_"
WHERE
"Company$Trans_ Sales Entry"."Date"='2014-05-16' AND
"Company$Archived Sales Entry"."Date"='2013-05-16'
GROUP BY
"Company$Trans_ Sales Entry"."Store No_",
"Company$Archived Sales Entry"."Store No_"
当我执行此查询时,我收到的数字" Sales"去年"去年"太高了。我的查询出了点问题......希望有人可以提供帮助!
如果我执行此操作,则销售数据是正确的,但之后我没有包括去年专栏:
Select
[Company$Trans_ Sales Entry].[Store No_] As Store,
Sum([Company$Trans_ Sales Entry].[Net Amount]) As Sales
From
[Company$Trans_ Sales Entry]
Where
[Company$Trans_ Sales Entry].Date = '2014-05-16'
Group By
[Company$Trans_ Sales Entry].[Store No_]
trans表和archived表中的每个商店都有多行,这就是为什么我需要对所有行进行求和并将它们分组到两个表中的每个商店。
答案 0 :(得分:3)
我怀疑在trans和archived表中每个商店有超过1行。如果是这样,那么您的查询注定要将结果相乘,因为引擎首先加入表,创建所有trans行的笛卡尔结果和同一商店的所有存档行,然后对值进行求和。因此,如果一个商店有2个trans行和3个存档行,那么在聚合之前将获得6行...并且在聚合和总和之后,“Sales”将是您期望的3倍,“去年”将是两次你期望的(对于那家商店)。
此查询可以解决您的问题。
SELECT
"Store No_" AS "Store",
SUM("Net Amount"*-1) AS "Sales",
(SELECT SUM("Net Amount"*-1)
FROM "Company$Archived Sales Entry"
WHERE
"Store No_"="Company$Trans_ Sales Entry"."Store No_" AND
"Date"='2013-05-16'
) AS "Last Year"
FROM "Company$Trans_ Sales Entry"
WHERE "Date"='2014-05-16'
GROUP BY "Store No_"
它对商店中的Trans表进行聚合和求和,为每个商店添加一个在Archived表上计算为sum的列...一个SUBSELECT。
另一种方法是首先对2个表进行聚合和求和,然后在商店中加入结果:
SELECT t.Store, Sales, "Last year"
FROM (SELECT "Store No_" AS "Store", SUM("Net Amount"*-1) AS "Sales"
FROM "Company$Trans_ Sales Entry"
WHERE "Date"='2014-05-16'
GROUP BY "Store No_") t
JOIN (SELECT "Store No_" AS "Store", SUM("Net Amount"*-1) AS "Last year"
FROM "Company$Archived Sales Entry"
WHERE "Date"='2013-05-16'
GROUP BY "Store No_") a
ON a.Store=t.Store
ORDER BY t.Store
请注意,如果Trans表和Archived表不包含所有相同的商店,则结果会有所不同。第一个将列出Trans表中找到的所有商店。第二个将仅列出两个表中的商店。