简体   繁体   中英

Excel vba ADODB.Connection Sql Count distincts

I am trying to count distincts

Sub sql(sqlStr As String, PasteRnG As Range)

Dim con As Object
Dim rstData As Object
Dim sDatabaseRangeAddress As String


    Set con = CreateObject("ADODB.Connection")
    Set rstData = CreateObject("ADODB.Recordset")

    con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ActiveWorkbook.FullName & ";Extended Properties = ""Excel 12.0 Macro;HDR=yes"";"
    rstData.Open sqlStr, con

    PasteRnG.CopyFromRecordset rstData

    rstData.Close
    Set rstData = Nothing
    Set con = Nothing

End Sub

query

sql "SELECT DISTINCT `P3`,`P2`,`P1`, COUNT(DISTINCT `P3`) AS countOf FROM [QQ$]  ", Worksheets("QQQQ").Range("a3")

error on

SELECT DISTINCT `P3`,`P2`,`P1`, COUNT(DISTINCT `P3`) AS countOf FROM table;

But I get error on COUNT(DISTINCT P3 )

I need to get in 4th column count of each DISTINCT P3

Distinctlist  P2   P1   CountOfDistinctInP3
    111 ,     11,  1,  56pcs.
    222,      22,  2,  25pcs.

P3 cannot be empty!!! Always have value

But this fine works like i need

sql "SELECT DISTINCT `P3`, COUNT(`P3`) FROM [QQ$] GROUP BY `P3` ", Worksheets("QQQQ").Range("a3")

But without P2 and P1 (((


尝试以下查询

select count (select distinct p3 from table) from table

尝试:

SELECT DISTINCT `P3`,`P2`,`P1`, COUNT( `P3`) AS countOf FROM table group by  `P3`

You SQL would seem to be trying to count the number of distinct values of P3 for each combined value of P1, P2 and P3. That will only ever be 0 (if P3 is NULL) or 1. However using an aggregate function (COUNT) will result in all rows being reduced to 1 row, hence P3 could have multiple values (and so a larger count), but the values of P1 and P2 would be undefined (they could have come from any row.

What you probably want is something like this:-

SELECT `P2`,`P1`, COUNT(DISTINCT `P3`) AS countOf 
FROM table
GROUP BY `P2`,`P1`;

Or if you need a list of the values of P3

SELECT `P2`,`P1`, COUNT(DISTINCT `P3`) AS countOf, GROUP_CONCAT(DISTINCT P3)
FROM table
GROUP BY `P2`,`P1`;

SELECT `P3`, `P2`,`P1`, COUNT(`P3`) AS countOf, GROUP_CONCAT(DISTINCT P3)
FROM table
GROUP BY `P3`, `P2`,`P1`;

解决后,SELECT中未聚合的每一列都必须位于GROUP BY子句中

sql "SELECT `P3`, `P2`, `P1`, COUNT(`P3`) FROM [QQ$] GROUP BY `P3`, `P2`, `P1` ", Worksheets("QQQQ").Range("a3")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM