*大家好,
我需要使用VBA SQl方法从多个字段中查找唯一值的计数,下面我提供了所有信息。
我的数据看起来像*
VC SMP# JDEStyle PO# QTY
ARU 10176 AM7619 F117849OG 64
ARU 10176 AM7619 F118215OG 192
ARU 10176 AM7619 F248062OD 336
ARU 653 AE7968 F114004O6 1
ARU 653 AE7968 F241623O4 18
ARU 653 AE7968 F8340O4 1
GOK 2061 SM8360 F248018OD 246
GOK 2061 SM8360 F248019OD 360
GOK 2061 SM8360 F248020OD 774
GOK 2061 SM8360 F248021OD 66
GOK 2061 SM8360 F248022OD 372
GOK 2061 SM8360 F256233OD 120
GOK 2061 SM8360 F256234OD 360
GOK 2061 SM8360 F256235OD 120
GOK 2061 SM8360 F256236OD 360
IND 10176 AB7049 F118324OG 217
IND 10176 AB7049 F258738OD 87
IND 10176 AB7049 F258739OD 540
IND 2068 AB7011 F114006O6 5
IND 2068 AB7011 F241625O4 3
SEP 10313 AL4596 F117270OG 4005
SEP 10313 AL4596 F118173OG 7911
SEP 10313 AL4596 F254362OD 540
SEP 10313 AL4596 F254365OD 150
,我期待的输出是
VC SMP # JDEStyle PO # QTY
ARU 10176 1 3 592
ARU 653 1 3 20
GOK 2061 1 9 2778
IND 10176 1 3 844
IND 2068 1 2 8
SEP 10313 1 4 12606
但我得到的输出就像
VC SMP # JDE Style Count of PO # Sum of QTY
ARU 10176 3 3 592
ARU 653 3 3 20
GOK 2061 9 9 2778
IND 10176 3 3 844
IND 2068 2 2 8
SEP 10313 4 4 12606
,我的代码是
Sub Quality_audit()
Dim query1 As String
Dim path As String
Dim i As Integer
Dim n As Integer
Dim m As Long
Dim wks As Worksheet
path = "U:\BA\Testing\QA\2014.09.29 SP 15 PROD FLW UP RAW DATA.xlsx"
query1 = "Select distinct [VC], [SMP #], Count([JDEStyle]) as 'JDE', Count ([PO #]) as PO, Sum ([Quantity]) as QTY from [Page 1$] where [SMP #] is not null AND ([VC] <> 'HEA' AND [VC] <> 'JMS' AND [VC] <> 'SJL') group by [VC], [SMP #]"
Set conn = New ADODB.Connection
With conn
.Provider = "microsoft.ace.oledb.12.0;"
.ConnectionString = "Data source = " & path & ";" & _
"extended properties = excel 12.0;"
.Open
End With
Set rs = New ADODB.Recordset
Set rs = conn.Execute(query1)
Workbooks.Add
Range("a2").CopyFromRecordset rs
n = 1
For i = 0 To rs.Fields.Count - 1
Cells(1, n).Value = rs.Fields(i).Name
n = n + 1
Next
rs.Close
conn.Close
end sub
您的帮助将不胜感激
答案 0 :(得分:0)
好吧,如果您的返回记录少于几千个,这里是您可能希望探索的替代解决方案。
公式为:
G2 - =IF(LEN(G1),IFERROR(INDEX(A$2:A$999, MATCH(0, IF(LEN(A$2:A$999), COUNTIFS($G$1:$G1,$A$2:$A$999,$H$1:$H1,$B$2:$B$999), 1),0)),""),"")
数组公式(Ctrl + Shift + Delete),复制到H2。
I2 - =IF(LEN($G2),SUMPRODUCT(($A$2:$A$999=$G2)*($B$2:$B$999=$H2)/COUNTIF(C$2:C$999, C$2:C$999&"")),"")
标准配方,复制到J2。
K2 - =IF(LEN(G2),SUMIFS($E$2:$E$999,$A$2:$A$999,$G2,$B$2:$B$999,$H2),"")
标准配方。根据需要填写所有五个公式以捕获您需要的记录。
您肯定知道,数组公式和SUMPRODUCT
无情地扼杀了计算资源。但是,如果考虑使用数据透视表,这可能是一个可行的选择。
答案 1 :(得分:0)
问题是你没有得到明确的计数吗?那么问题就在于SQL,是吗?我认为你的DISTINCT在错误的地方。
Select
vc,
smp,
Count(distinct jdestyle) as 'JDE',
Count (distinct po) as 'PO',
Sum (qty) as 'QTY'
from stuff
group by VC, SMP;