0

我需要在 SQL Server 中制作一份自定义报告。我有一张名为 ProductsTable 的表,在这张表中有价格的产品表。

| id | description |
| 1  |   TABLE A   |
| 2  |   TABLE B   |
| 3  |   TABLE C   |
| 4  |   TABLE D   |

现在,我有表格 ProductsTablePrices 与所有产品价格和他的表格。

| id | idproduct | idtable | price |
| 1  | 1         | 1       | 1.00  |
| 1  | 1         | 2       | 1.50  |
| 1  | 1         | 3       | 2.00  |
| 1  | 1         | 4       | 5.00  |

最后,我有 Products 表。

| id |   name   |
| 1  | Paper    |

我需要创建一个选择来获得这样的一个结果......

| name  | TABLE A | TABLE B | TABLE C | TABLE D |
| Paper |  1.00   |   1.50  |   2.00  |   5.00  |

谢谢!

4

2 回答 2

1

试试这个:

SELECT
   P.name,
   SUM(CASE WHEN PT.description = 'TABLE A' THEN PP.price END) [TABLE A],
   SUM(CASE WHEN PT.description = 'TABLE B' THEN PP.price END) [TABLE B],
   SUM(CASE WHEN PT.description = 'TABLE C' THEN PP.price END) [TABLE C],
   SUM(CASE WHEN PT.description = 'TABLE D' THEN PP.price END) [TABLE D]
FROM Products P
   JOIN ProductsTablePrices PP
      ON P.id = PP.idproduct
   JOIN ProductsTable PT
      ON PP.idtable = PT.id
GROUP BY P.name
于 2013-01-31T18:10:08.620 回答
0

我用它来解决我的问题。

DECLARE @NameColumnTable VARCHAR(100)
DECLARE @CountColumns INT
DECLARE @ColumnsPivot varchar(6000)
DECLARE @Flag INT

SELECT @CountColumns = count(*) FROM ProductsTable
SET @Flag = 0

WHILE (@Flag <= @CountColumns)
BEGIN
    SELECT @NameColumnTable = Name FROM ProductsTable
    WHERE id = @Flag
    ORDER BY Name ASC

    SET @ColumnsPivot = ISNULL(@ColumnsPivot,'') + 'SUM(CASE WHEN PT.description = ''' + @NameColumnTable + ''' THEN PP.price END) [' + @NameColumnTable + ']'

    IF @Flag <> @CountColumns
    BEGIN
      SET @ColumnsPivot = @ColumnsPivot + ','
    END

    SET @ColumnsPivot = @ColumnsPivot + CHAR(13)

SET @Flag = @Flag + 1
END

DECLARE @SQLFINAL VARCHAR(5000)

SET @SQLFINAL = 'SELECT  
                   P.name,
                   ' + @ColumnsPivot + '
                FROM Products P
                JOIN ProductsTablePrices PP
                    ON P.id = PP.idproduct
                JOIN ProductsTable PT
                    ON PP.idtable = PT.id
                GROUP BY P.name
                ORDER BY P.name'
EXEC(@SQLFINAL)

我不知道这是否是一个好习惯,但效果很好,性能也很好。

谢谢!

于 2013-01-31T20:23:34.783 回答