SQL Server总查询

时间:2016-04-26 02:56:50

标签: sql sql-server pivot

我需要一个总和其他列的查询

mnist.train.next_batch()

按用户和日期过滤的日期之间的结果应该是:

2016年1月3日至2016年3月31日

User     sales    amount    date
--------------------------------------
danny    car      10.000    25/02/2016
danny    moto      5.000    26/02/2016
danny    car      10.000    25/03/2016
danny    moto      5.000    26/03/2016
danny    moto      5.000    26/03/2016
danny    car      10.000    25/04/2016
danny    moto      5.000    26/04/2016
danny    car      10.000    25/05/2016
danny    moto      5.000    26/05/2016

我需要什么查询?

3 个答案:

答案 0 :(得分:1)

尝试Pivot

SELECT * FROM 
(
   SELECT User,sales,amount,datename(month, date)
   FROM YoyrTable   
)A
PIVOT
(
   SUM(amount)
   FOR sales in ([car],[moto])
)B

答案 1 :(得分:1)

另一种方法:

;WITH cte AS (
SELECT *
FROM (VALUES
('danny', 'car', 10.000, '2016-02-15'),
('danny', 'moto', 5.000, '2016-02-26'),
('danny', 'car', 10.000, '2016-03-25'),
('danny', 'moto', 5.000, '2016-03-26'),
('danny', 'moto', 5.000, '2016-03-26'),
('danny', 'car', 10.000, '2016-04-25'),
('danny', 'moto', 5.000, '2016-04-26'),
('danny', 'car',  10.000, '2016-05-25'),
('danny', 'moto', 5.000, '2016-05-26')
) as t([User], sales, amount, [date])
)

SELECT  [user],
        SUM(amount) as Total,
        SUM(CASE WHEN sales = 'moto' THEN 1 ELSE 0 END) as moto,
        SUM(CASE WHEN sales = 'car' THEN 1 ELSE 0 END) as car,
        DATENAME(Month,[date]) as [date]
FROM cte
GROUP BY [user], DATENAME(Month,[date]),DATEPART(Month,[date]), DATEPART(Year,[date])
ORDER BY DATEPART(Month,[date]), DATEPART(Year,[date])

输出:

user    Total   moto    car date
danny   15.000  1       1   February
danny   20.000  2       1   March
danny   15.000  1       1   April
danny   15.000  1       1   May

在查询中,将您的表名改为cte

答案 2 :(得分:1)

您的实际PIVOT应该是什么样的..

SELECT  [User],
        Total,
        [moto],
        [car],
        [date] 
FROM 
(
    SELECT  [User],
            sales,
            DATENAME(MONTH,date) [date],
            SUM(amount) OVER (PARTITION BY [User], DATENAME(MONTH,date)) [Total]
    FROM    cte
) T
PIVOT
(
    COUNT(sales)
    FOR sales IN ([car], [moto])
) p

@ gofr1的回答应该会更好。