我正在为所有行获取相同的列计数如何在SQL中有效地计算列值的出现次数?

时间:2019-02-20 04:52:00

标签: sql sql-server-2008-r2

Select 
       Sales_Detail.Serial_No
       ,Sales_Detail.Tax_Percentage
       ,Card_Amount
       ,Cash_Amount
       ,ISNULL((Select  Count(DISTINCT  Tax_Percentage) From Sales_Detail
        Left Join Sales_Master  ON 
        Sales_Master.Serial_No=Sales_Detail.Serial_No
        Where Sales_Master.Invoice_Date = '14-Feb-2019' 
       And IsSaved='True'And IsCancelled = 'False'
       And Card_Amount >0 Or Sales_Master.Cash_Amount>0 
       And Sales_Detail.Serial_No=10467),1) As Count_Tax    

From Sales_Detail    
Inner Join Item_Master On Sales_Detail.Item_ID = Item_Master.Item_ID
Inner Join Item_Brand On Item_Master.Brand_ID = Item_Brand.Brand_ID
Inner Join Sales_Master On Sales_Detail.Serial_No=Sales_Master.Serial_No
left Join Customer C on C.Customer_ID =Sales_Master.Customer_ID     
Inner Join Tax On Tax.Tax_Percentage=Sales_Detail.Tax_Percentage 

Where Sales_Master.Invoice_Date = '14-Feb-2019' And IsSaved = 'True' 
And IsCancelled = 'False'
order by Sales_Detail.SGST_Percentage ,Tax_Percentage

从上述查询中计数时。 我将所有行的计数都设为2。为什么会这样呢? 如果在查询中选择以上选项,则预期所有行的输出计数为2, 但是实际上我想将序列号10467的计数设置为1,将序列号10468的计数设置为2。

Select
     Count(DISTINCT Tax_Percentage)
  From Sales_Detail

  Left Join Sales_Master ON Sales_Master.Serial_No=Sales_Detail.Serial_No

  Where Sales_Master.Invoice_Date = '14-Feb-2019'
  And IsSaved='True'And IsCancelled = 'False'
  And Card_Amount >0 Or Sales_Master.Cash_Amount>0
  And Sales_Detail.Serial_No=10467

enter image description here

1 个答案:

答案 0 :(得分:0)

在选择中,您正在对Searial_No And Sales_Detail.Serial_No=10467进行硬编码,因此对于每一行,您将获得相同的值。

更改喜欢的人。

Select 
       Sales_Detail.Serial_No
       ,Sales_Detail.Tax_Percentage
       ,Card_Amount
       ,Cash_Amount
       ,ISNULL((Select  Count(DISTINCT  Tax_Percentage) From Sales_Detail SD
        Left Join Sales_Master  ON 
        Sales_Master.Serial_No=SD.Serial_No
        Where Sales_Master.Invoice_Date = '14-Feb-2019' 
       And IsSaved='True'And IsCancelled = 'False'
       And Card_Amount >0 Or Sales_Master.Cash_Amount>0 
       And SD.Serial_No=Sales_Detail.Serial_No     
       ),1) As Count_Tax    

From Sales_Detail    
Inner Join Item_Master On Sales_Detail.Item_ID = Item_Master.Item_ID
Inner Join Item_Brand On Item_Master.Brand_ID = Item_Brand.Brand_ID
Inner Join Sales_Master On Sales_Detail.Serial_No=Sales_Master.Serial_No
left Join Customer C on C.Customer_ID =Sales_Master.Customer_ID     
Inner Join Tax On Tax.Tax_Percentage=Sales_Detail.Tax_Percentage 

Where Sales_Master.Invoice_Date = '14-Feb-2019' And IsSaved = 'True' 
And IsCancelled = 'False'
order by Sales_Detail.SGST_Percentage ,Tax_Percentage

建议:作为一项好习惯,请始终对表使用别名,以便可以在多个位置轻松使用它而不会引起混淆。