将MS Access计数和数据透视查询转换为SQL Server

时间:2015-10-10 17:14:40

标签: sql-server ms-access count pivot-table

我有杂货店数据库。我想要计算收据中每个类别的产品数量。

表格是:

  • Transactions(id_transaction,quantity,id_receipt,id_product)
  • Receipts(id_receipt,date,id_store,id_customer)
  • Products(id_product,product_name,price,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

1 个答案:

答案 0 :(得分:0)

基本上,这是经典的转置查询。考虑以下SQL,它应该符合大多数RDMS的要求。对于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 ;