[英]How can I display a consolidated version of my SQL Server table?
Consider this simplified scenario for an SQL Server database. 考虑针对SQL Server数据库的简化方案。 This is not exactly the way my tables are built, but the example is enough for what I need to know.
这并不完全是我的表的构建方式,但是该示例足以满足我的需要。
I have a product table with a primary key, let's say, IdProduct
, and some other columns, like the product name and description. 我有一个带有主键的产品表,比方说,
IdProduct
和其他一些列,例如产品名称和描述。
Then I have something like a total sales per month table ( SalesPerMonth
). 然后,我有类似每月总销售额的表格(
SalesPerMonth
)。 This second table holds some fields like: 第二个表包含一些字段,例如:
IdMonthlySale (key)
IdProduct (foreign key to the main table)
TotalSales (money)
Monthy (int or smallint)
Year (int or smallint)
The second table will hold the detailed info. 第二个表将包含详细信息。 We can track the sales of a certain product by doing a
SELECT * FROM SalesPerMonth WHERE ProductId = xx
我们可以通过执行
SELECT * FROM SalesPerMonth WHERE ProductId = xx
来跟踪特定产品的销售情况
But let's say I want to display this data as if it wasn't normalized. 但是,假设我要显示此数据,就好像未对其进行规范化一样。 I want a flat Product X Month/Year table that shows the last 8 months.
我想要一个显示最近8个月的固定产品X月/年表。 Something more or less like this:
大概是这样的:
Prod * Jan * Feb * Mar * Apr * May * Jun * Jul * Aug *
-----------------------------------------------------------------------------
Prod 1 * 500.00* 480.00* 470.00* 510.00* 555.00* 530.00* 440.00* 490.00*
-----------------------------------------------------------------------------
Prod 2 * 650.00* 680.00* 670.00* 710.00* 755.00* 630.00* 740.00* 820.00*
Well. 好。 I hope you get the idea.
希望您能明白。 I need to flatten the resulting table and I need to output it that way to my users.
我需要展平结果表,然后以这种方式将其输出给我的用户。 How can I accomplish that?
我该怎么做?
Starting with SQL Server 2005 you can use PIVOT to do this 从SQL Server 2005开始,您可以使用PIVOT进行此操作
In SQL 2000 you can use a series of CASE statement eg 在SQL 2000中,您可以使用一系列CASE语句,例如
SELECT
SUM(CASE WHEN Month = 1 THEN Value ELSE 0 END ) as Jan,
SUM(CASE WHEN Month = 2 THEN Value ELSE 0 END ) as Feb,
If you don't care about the field names you can use offset off an input. 如果您不关心字段名称,则可以使用offset off输入。
DECLARE @CurrentMonth = @Input;
DECLARE @CurrentMonth1 = @Input -1;
DECLARE @CurrentMonth2 = @Input -2;
and then do your SUM/CASE off that 然后做你的求和/案例
e.g.
SUM(CASE WHEN Month = @CurrentMonth THEN Value ELSE 0 END ) as Month0,
SUM(CASE WHEN Month = @CurrentMonth1 THEN Value ELSE 0 END ) as Month1,
Then in your display (report/application) you resolve what to put as column headings 然后在您的显示(报告/应用程序)中,确定要放置为列标题的内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.