开发者

How can I display a consolidated version of my SQL Server table?

Consider this simplified scenario for an SQL Server database. 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.

Then I have something like a total sales per month table (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

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. 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

In SQL 2000 you can use a series of CASE statement e.g.

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.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜