每个商店最常用的是tendertype T-SQL

时间:2014-10-16 18:12:35

标签: sql sql-server tsql

我需要一些帮助来构建这个MSSQL查询。 我有一张包含付款信息的表格。 在表格" payment_entry"是Storenumber和Tendertype的字段。 每次新购买都会在表格中创建一个新行" payment_entry"用" store"和" tendertype"。 有两种类型" 1"或" 3"。 1表示信用卡/借记卡,3表示现金。

我想要一个按商店分组的查询,每个商店中有多少客户支付现金以及用卡支付多少钱。

提前致谢!! 编辑: 好吧我不擅长SQL但这给了我一个计数每个商店的tendertype 1 ..现在我卡住..

Select [company$Trans_ Payment Entry].[Store No_], 
Count([company$Trans_ Payment Entry].[Tender Type]) 
From [company$Trans_ Payment Entry] [company$Trans_ Payment Entry] 
Where [company$Trans_ Payment Entry].[Tender Type] = '1' 
Group By [company$Trans_ Payment Entry].[Store No_] 
Order By [company$Trans_ Payment Entry].[Store No_] 

2 个答案:

答案 0 :(得分:1)

您可以使用基于CASE的聚合

来完成此操作
SELECT store, 
       (SUM(CASE WHEN tendertype =1 THEN 1 ELSE 0 END)*100.0/COUNT(tenderType)) AS CreditPerc,
       SUM(CASE WHEN tendertype =3 THEN 1 ELSE 0 END)*100.0/COUNT(tenderType) as CashPerc
FROM payment_entry
GROUP BY store

答案 1 :(得分:1)

;WITH Store_Totals AS
 (
  SELECT [Store No_] AS StoreNum
        ,SUM(CASE WHEN tendertypes = 1 THEN 1 ELSE 0 END) AS Credit_Trans
        ,SUM(CASE WHEN tendertypes = 3 THEN 1 ELSE 0 END) AS Cash_Trans
        ,COUNT(tendertypes)  AS Total_Trans
  FROM [company$Trans_ Payment Entry]
  GROUP BY [Store No_]
 )
SELECT  StoreNum
       ,Credit_Trans / Total_Trans AS Average_Credit
       ,Cash_Trans   / Total_Trans AS Average_Cash
FROM Store_Totals