SQL Server返回不同的行?



我正在运行这个SQL语句:

SELECT   
s.indx, S.custid, S.date, S.qty, S.item, S.price, S.extprice, 
S.salestax, S.linetotal, S.salenbr, C.company, P.MOP
FROM            
sales S
JOIN
cust C ON S.custid = C.custid
JOIN
pmts P ON S.salenbr = p.salenbr
WHERE        
(s.salenbr = 16749)

返回这个结果集:

indx    custid  date    qty item    price   extprice    salestax    linetotal   salenbr company MOP
170835  695 2021-09-27 10:00:44.000 1.00    1X4X12  7.85    7.85    0.75    8.60    16749   COUNTER SALE    CS   
170835  695 2021-09-27 10:00:44.000 1.00    1X4X12  7.85    7.85    0.75    8.60    16749   COUNTER SALE    CC   
170836  695 2021-09-27 10:00:44.000 1.00    1X6X12  11.62   11.62   1.10    12.72   16749   COUNTER SALE    CS   
170836  695 2021-09-27 10:00:44.000 1.00    1X6X12  11.62   11.62   1.10    12.72   16749   COUNTER SALE    CC   

我只想拉出支付方式"MOP"是不同的。我正在使用数据来运行报告,并且只需要它具有不同或唯一的MOP。

谢谢

您可以在这里使用ROW_NUMBER任意取"first"每个MOP组的记录,按一定顺序:

WITH cte AS (
SELECT s.indx, S.custid, S.date, S.qty, S.item, S.price, S.extprice, 
S.salestax, S.linetotal, S.salenbr, C.company, P.MOP,
ROW_NUMBER() OVER (PARTITION BY P.MOP ORDER BY S.date) rn
FROM sales S
INNER JOIN cust C ON S.custid = C.custid
INNER JOIN pmts P ON S.salenbr = P.salenbr
WHERE S.salenbr = 16749
)
SELECT indx, custid, date, qty, item, price, exitprice,
salestax, linetotal, salenbr, company, MOP
FROM cte
WHERE rn = 1;

因此,使用公共表表达式或CTE可能会更好。像这样:

WITH CTE_Sales AS
(
SELECT
s.indx, S.custid, S.date, S.qty, S.item, S.price, S.extprice, 
S.salestax, S.linetotal, S.salenbr, C.company, P.MOP, 
COUNT(1) AS salesCount
FROM
sales S
JOIN
cust C ON S.custid = C.custid
JOIN
pmts P ON S.salenbr = p.salenbr
GROUP BY
s.indx, S.custid, S.date, S.qty, S.item, S.price, S.extprice,
S.salestax, S.linetotal, S.salenbr, C.company, P.MOP
)
SELECT     
indx, custid, date, qty, item, price, extprice, 
salestax, linetotal, salenbr, company 
FROM
CTE_Sales
GROUP BY 
indx, custid, date, qty, item, price, extprice, 
salestax, linetotal, salenbr, company
HAVING 
salesCount > 1

这样做的作用是CTE包含所有数据,这使得不需要每次都处理连接变得更容易。你还做了一个分组,这样你就知道同样的销售有多少张唱片。

然后,当您提取数据时,您在没有MOP的情况下对记录进行分组。由于第一个记录使用MOP分组,而第二个记录不使用MOP分组,因此您知道MOPs是不同的。

我认为我需要回去做一些重新设计在我的代码和数据表SMor你是正确的细节与事务。活到老学到老:)感谢大家抽出时间来回复。我是一个人工作,所以听到别人的意见和想法总是很棒的。谢谢!

最新更新