在Select和全局Where语句中使用Where语句

时间:2016-01-29 16:37:05

标签: sql sql-server

我正在尝试运行此查询。我需要在Select语句中使用where语句,但我还需要一个全局Where语句来将我的数据优化到特定时间。此查询给出了错误

  

"消息207,级别16,状态1,行20无效的列名称   ' TransactionDateTime'"

我知道我可以将日期Where语句添加到每一行,但是当我必须更改那些会很痛苦的日期时。

任何帮助都将不胜感激。

Select (Select count(Paymentmethod)
from [CLIENT-PROD-POS].dbo.POS_Payments
where paymentmethod ='1') 
as Cash,

(Select count(Paymentmethod)
from [CLIENT-PROD-POS].dbo.POS_Payments
where paymentmethod ='2')
as PaperChecks,

(Select count(Paymentmethod)
from [CLIENT-PROD-POS].dbo.POS_Payments
where paymentmethod ='3')
as CreditCards,

(Select count(Paymentmethod)
from [CLIENT-PROD-POS].dbo.POS_Payments
where paymentmethod ='5')
as EChecks

where TransactionDateTime > '1/1/2015' and transactiondatetime < '2/1/2015'

2 个答案:

答案 0 :(得分:4)

要解决此错误,您需要在每个TransactionDateTime中添加sub-query个文件管理器。

您不需要多个sub-queries来计算每个paymentmethod。试试这个

SELECT Count(CASE WHEN paymentmethod = '1' THEN Paymentmethod END) AS Cash,
       Count(CASE WHEN paymentmethod = '2' THEN Paymentmethod END) AS PaperChecks,
       Count(CASE WHEN paymentmethod = '3' THEN Paymentmethod END) AS CreditCards,
       Count(CASE WHEN paymentmethod = '5' THEN Paymentmethod END) AS EChecks
FROM   [CLIENT-PROD-POS].dbo.POS_Payments
WHERE  TransactionDateTime > '1/1/2015'
       AND transactiondatetime < '2/1/2015'
       AND paymentmethod IN ( 1, 2, 3, 5 ) 

另一种计算方法是

sum(case when paymentmethod ='1' then 1 else 0 end) as Cash

答案 1 :(得分:3)

使用条件聚合:

Select sum(case when paymentmethod = '1' then 1 else 0 end) as Cash,
       sum(case when paymentmethod = '2' then 1 else 0 end) as PaperChecks,
       sum(case when paymentmethod = '3' then 1 else 0 end) as CreditCards,
       sum(case when paymentmethod = '4' then 1 else 0 end) as EChecks
from [CLIENT-PROD-POS].dbo.POS_Payments
where TransactionDateTime > '2015-01-01' and
      transactiondatetime < '2015-02-01';

我还强烈建议您使用日期的标准格式 - YYYY-MM-DD。