2015-10-10 64 views
1

我有雜貨店數據庫。我想統計每個類別的收據上有多少產品。將MS Access計數和數據透視查詢轉換爲SQL Server

表是:

  • Transactions(id_transaction,數量,id_receipt,id_product)
  • Receipts(id_receipt,日期,id_store,id_customer)
  • Products(id_product,PRODUCT_NAME,價格,id_prod_cat)
  • Product_Categories(id_prod_cat,category_name)

所需的輸出與樣本數據:

ID_RECEIPT | desserts | meat | juices | baker products| canned | 
-------------------------------------------------------------------| 
1   | 0  | 2 | 1  |  3   | 0 | 
2   | 1  | 0 | 3  |  1   | 0 | 
-------------------------------------------------------------------- 

我已經試過此查詢,但沒有成功。

TRANSFORM Nz(Count(dbo.Transactions.quantity), 0) AS Product Count 
SELECT dbo.Receipts.id_receipt 
FROM dbo.Product_Categories 
INNER JOIN (dbo.Receipts 
    INNER JOIN (dbo.PRODUCTS 
     INNER JOIN dbo.TRANSACTIONS ON dbo.PRODUCTS.id_product = dbo.TRANSACTIONS.id_product) 
     ON dbo.RECEIPTS.id_receipt = dbo.TRANSACTIONS.id_receipt) 
    ON dbo.Product_Categories.id_prod_cut = dbo.Products.id_product 
GROUP BY 
    dbo.Receipts.id_receipt 
PIVOT 
    dbo.Product_Categories.category_name 

回答

0

實質上,這是經典轉置查詢。考慮以下在大多數RDMS中應該符合的SQL。對於MS Access,您將使用IIF()而不是CASE WHEN(和連接中的括號)。與Transform交叉表查詢主要是MS Access類型,而Pivot()主要是SQL Server功能。但是,下面應該跨數據庫方言。

SELECT 
    dbo.Receipts.id_receipt, 
    Count(CASE WHEN dbo.Product_Categories.category_name='desserts' 
       THEN dbo.Transactions.quantity END) As [desserts], 
    Count(CASE WHEN dbo.Product_Categories.category_name='meat' 
       THEN dbo.Transactions.quantity END) As [meat], 
    Count(CASE WHEN dbo.Product_Categories.category_name='juices' 
       THEN dbo.Transactions.quantity END) As [juices], 
    Count(CASE WHEN dbo.Product_Categories.category_name='baker products' 
       THEN dbo.Transactions.quantity END) As [baker products], 
    Count(CASE WHEN dbo.Product_Categories.category_name='canned' 
       THEN dbo.Transactions.quantity END) As [canned] 

FROM dbo.Product_Categories 
INNER JOIN dbo.Receipts 
INNER JOIN dbo.PRODUCTS 
INNER JOIN dbo.TRANSACTIONS ON dbo.PRODUCTS.id_product = dbo.TRANSACTIONS.id_product 
    ON dbo.RECEIPTS.id_receipt = dbo.TRANSACTIONS.id_receipt 
    ON dbo.Product_Categories.id_prod_cut = dbo.Products.id_product 

GROUP BY dbo.Receipts.id_receipt ; 
+0

謝謝先生,它的工作,但更重要的是,我看到我做錯了什麼。 –