Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Subtotal dan SQL

Lihat sesuatu seperti

DECLARE @Sales TABLE(
        CUS_ID  INT,
        PRODUCT VARCHAR(20),
        AMOUNT FLOAT
)
INSERT INTO @Sales SELECT 12,'A', 2.50 
INSERT INTO @Sales SELECT 12,'B', 5.80 
INSERT INTO @Sales SELECT 24,'A', 10.00 
INSERT INTO @Sales SELECT 24,'B', 30.00

;WITH Vals AS (
        SELECT  cus_id, 
                product, 
                amount,
                1 DisplayOrder,
                SUM(amount) OVER(PARTITION BY cus_id) OrderTotal
        FROM    @Sales 
        UNION ALL   
        SELECT  cus_id, 
                'Total' AS product, 
                SUM(amount),
                2 DisplayOrder,
                SUM(amount)
        FROM    @Sales 
        GROUP BY cus_id
)
SELECT  cus_id,
        product,
        amount
FROM    Vals
ORDER BY  OrderTotal DESC,cus_id,DisplayOrder, product 


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Menggunakan variabel dalam pernyataan SEPERTI SQL

  2. Ubah 'smalldatetime' menjadi 'datetime2' di SQL Server (Contoh T-SQL)

  3. Bisakah Anda memiliki logika if-then-else dalam SQL?

  4. Pengantar Fungsi Bernilai Tabel Multi-Pernyataan (MSTVF) di SQL Server

  5. SQL:Kesalahan, batas layanan Ekspresi tercapai?