我想透视表

时间:2018-11-20 06:49:14

标签: sql sql-server sql-server-2012

我想按照以下给定的格式对数据进行分类, 在下面的代码中,我放置了一个代码来创建具有我已经拥有的数据的表。

CREATE TABLE #temp
(
SHOW     VARCHAR(100),
moviename    VARCHAR(100),
ticketrate    INT,
collectiondate    DATETIME,
totalcaroccupancy  DECIMAL(18,2)
)

INSERT INTO #temp
(
SHOW,
moviename,
ticketrate,
collectiondate,
totalcaroccupancy
)
SELECT 'Evening','DASSEHRA',70,'2018-10-26 00:00:00.000','11440.00' union all
SELECT 'Evening','DASSEHRA',70,'2018-10-27 00:00:00.000','16016.00' union all
SELECT 'Night','Test Thugs',70,'2018-10-26 00:00:00.000','14560.00' union all
SELECT 'Night','Test Thugs',70,'2018-10-27 00:00:00.000','15600.00'

我当前的表格数据如下:

SHOW       moviename     ticketrate    collectiondate      totalcaroccupancy
Evening    DASSEHRA      70            2018-10-26 00:00:00.000    11440.00
Evening    DASSEHRA      70            2018-10-27 00:00:00.000    16016.00
Night      Test Thugs    70            2018-10-26 00:00:00.000    14560.00
Night      Test Thugs    70            2018-10-27 00:00:00.000    15600.00

我希望输出如下:

collectiondate             eveningticketrate    eveningticketrate    eveningMovieName    nightMovieName    eveningtotalcaroccupancy    nighttotalcaroccupancy
2018-10-26 00:00:00.000    70                   70                   DASSEHRA            Test Thugs        11440.00                    14560.00
2018-10-27 00:00:00.000    70                   70                   DASSEHRA            Test Thugs        16016.00                    15600.00

2 个答案:

答案 0 :(得分:4)

仅使用如下所示的条件案例语句

select  collectiondate,
    max(case when SHOW = 'Evening' then ticketrate end) as eveningticketrate,
    max(case when SHOW = 'Night' then ticketrate end) as nightticketrate,
    max(case when SHOW = 'Evening' then moviename end) as eveningmoviename,
    max(case when SHOW = 'Night' then moviename end) as nightmoviename,
    max(case when SHOW = 'Evening' then totalcaroccupancy end) as eveningtotalcaroccupancy,
    max(case when SHOW = 'Night' then totalcaroccupancy end) as nighttotalcaroccupancy
from    #temp
group by collectiondate

答案 1 :(得分:0)

另一种方法是创建2个子查询,一个子查询为晚上,另一个子查询为晚上并将它们连接在一起

SELECT evening.collectiondate, eveningticketrate, eveningmoviename, eveningtotalcaroccupancy,
    nightticketrate, nightmoviename, nighttotalcaroccupancy
FROM (
    SELECT collectiondate, ticketrate as eveningticketrate, moviename as eveningmoviename, totalcaroccupancy as eveningtotalcaroccupancy
    FROM #temp
    WHERE show = 'Evening') evening
INNER JOIN (
    SELECT collectiondate, ticketrate as nightticketrate, moviename as nightmoviename, totalcaroccupancy as nighttotalcaroccupancy
    FROM #temp
    WHERE show = 'Night') night ON evening.collectiondate = night.collectiondate
ORDER BY evening.collectiondate;