GR_NO| Month_ID | Amount
43 | 7 | $200.00
43 | 8 | $300.00
43 | 9 | $500.00
show应该是这样的
GR_NO | 7 | 8 | 9 |
43 | $200.00 | $300.00 |$500.00
答案 0 :(得分:0)
SELECT GR_NO, [7], [8], [9]
FROM
(SELECT GR_NO, Month, Amount From Database.schema.TableName)
AS SourceTable
PIVOT
(
Sum(Amount)
FOR Month IN ( [7], [8], [9])
) AS PivotTable;
--<optional ORDER BY clause>;
我通过查看数据透视表信息来研究这个答案:https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
使用MSSQL
结果
GR_NO 7 8 9
43 200.00 200.00 500.00
答案 1 :(得分:0)
由于我不知道您使用的是哪种类型的SQL,因此该示例采用MS T-SQL 2014风格。它应该与大多数其他类型的SQL类似。
首先,我们设置测试表和数据。
MS SQL Server 2014架构设置:
CREATE TABLE t1 ( GR_NO int, Month_ID int, Amount decimal(10,2) ) ;
INSERT INTO t1 ( GR_NO, Month_ID, Amount )
VALUES
( 43, 7, 200.00 )
, ( 43, 8, 300.00 )
, ( 43, 9, 500.00 )
, ( 44, 2, 100.00 )
, ( 43, 2, 250.00 ) /* Out of cycle */
, ( 43, 4, 10.00 ) /* Aggregate 1 */
, ( 43, 4, 10.00 ) /* Aggregate 2 */
;
这是您的Pivot查询:
SELECT p.GR_NO
, p.[1] AS Jan
, p.[2] AS Feb
, p.[3] AS Mar
, p.[4] AS Apr /* Look at aggregated example. */
, p.[5] AS May
, p.[6] AS Jun
, p.[7] AS Jul
, p.[8] AS Aug
, p.[9] AS Sep
, p.[10] AS Oct
, p.[11] AS Nov
, p.[12] AS Dec
/* After the pivot, columns come from p. */
FROM (
SELECT GR_NO, Month_ID, Amount
FROM t1
/* Source table for pivoting data. */
) s
PIVOT (
SUM(Amount) /* Has to be an aggregate function. */
FOR Month_ID IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
/* These are the fields you'd like to end up in the pivot. */
) p
这给了我们:
<强> Results 强>:
| GR_NO | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec |
|-------|--------|-----|--------|--------|--------|--------|--------|--------|--------|--------|--------|--------|
| 43 | (null) | 250 | (null) | 20 | (null) | (null) | 200 | 300 | 500 | (null) | (null) | (null) |
| 44 | (null) | 100 | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) |