简体   繁体   中英

Total SQL Server query

I need a query that totals with sum others columns

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

Result between dates filter by user and date should by:

between 01/03/2016 and 31/03/2016

User   Total   moto    car     
------------------------------
danny  15.000  2        1       

What query do I need?

Try Pivot

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

Another approach:

;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])

Output:

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

In query put your table name instead cte

what your actual PIVOT should look like..

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

the answer by @gofr1 should perform better though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM