我是新手并在Microsoft SQL Server 2008上学习SQL。我正在尝试对订单行项目表执行以下操作,每个记录都是一个订单项。 任何只有一条记录和代码为#####的交易号。 我尝试了很多方法,但一直无法弄清楚
Select * from Table
where count(transactionnumber)<2 and Code='9987'
我想我明白了。不得不使用不同的代码,因为QA没有与该代码不同的行。如果您发现可能导致问题的任何问题,请告诉我。
Select * from (select Orders.TransactionNumber from Orders
group by Orders.TransactionNumber
having COUNT (Orders.TransactionNumber)=1) as transa
Inner join Orders on transa.TransactionNumber=Orders.TransactionNumber
where ItemCode=9803
结束此代码
use XXX
Select Orders.TransactionNumber,Orders.RepNumber, Orders.CustomerID,Orders.ShipToId,orders.ItemCode,Orders.Quantity,Orders.ReceivedDate,Orders.TransmitStatus from (select TransactionNumber from Orders
group by TransactionNumber
having COUNT (TransactionNumber)=1) as transa
Inner join Orders on Orders.TransactionNumber=transa.TransactionNumber
where ItemCode=9987 and ReceivedDate > DateADD (day, -1, GetDate() )
IF @@ROWCOUNT > 0
BEGIN
EXEC msdb.dbo.sp_send_dbmail
recipients=N'XXXX',
@body='Merchandisers orders with only Item Code 9803',
@subject ='only Item Code 9803',
@profile_name ='',
@query = 'Select Orders.TransactionNumber,Orders.RepNumber,Orders.CustomerID,Orders.ShipToId,orders.ItemCode,Orders.Quantity,Orders.ReceivedDate,Orders.TransmitStatus from(select TransactionNumber from Orders
group by TransactionNumber
having COUNT (TransactionNumber)<2) as transa
Inner join Orders on Orders.TransactionNumber=transa.TransactionNumber
where ItemCode=9803 and ReceivedDate > DateADD (day, -1, GetDate() )'
END'
答案 0 :(得分:0)
您的查询应该包含要分组的内容(Name,TransactionNumber等)进行计数和约束。
SELECT TransactionCode, COUNT(*)
FROM TABLE
GROUP BY TransactionCode
HAVING COUNT(*) < 2
AND ItemCode = 9987
答案 1 :(得分:0)
您可以考虑使用OVER
关键字,这样就不需要在count(*)
和group by
周围捣乱了。这样你就可以在没有分组的情况下看到计数。
Select *, count(*) over (partition by transactioncode) as "TheCounts"
from table
--where itemcode = 9903
或
Select *, count(*) over (partition by transactioncode, itemcode) as "TheCounts"
from table
--where itemcode = 9903
答案 2 :(得分:0)
以下是我最终得到的结果似乎正常工作大约一周,现在它只在有记录时执行sp_send_dbmail。
Select Orders.TransactionNumber, Orders.RepNumber, Orders.CustomerID,Orders.ShipToId,orders.ItemCode,Orders.Quantity,Orders.ReceivedDate,Orders.TransmitStatus from (select TransactionNumber from Orders
group by TransactionNumber
having COUNT (TransactionNumber)=1) as transa
Inner join Device_Orders on Orders.TransactionNumber=transa.TransactionNumber
where ItemCode=9987 and ReceivedDate > DateADD (day, -1, GetDate() )
IF @@ROWCOUNT > 0