June 18, 2013 at 11:54 am
Is there a way to structure a single query to select all the unique values from field 1 of table A, and the unique values from field 2 of Table A and then select count(*) for all of the resulting combinations of field 1 and field 2 values?
Thanks in advance.
June 18, 2013 at 12:02 pm
RPSql (6/18/2013)
Is there a way to structure a single query to select all the unique values from field 1 of table A, and the unique values from field 2 of Table A and then select count(*) for all of the resulting combinations of field 1 and field 2 values?Thanks in advance.
maybe something like this?
the UNION will merge duplicates between the two tables.
SELECT
COUNT(Columnname) As TotalCount
FROM (
SELECT DISTINCT ColumnName FROM Table1
UNION
SELECT DISTINCT OtherColumnName FROM Table2
)MyAlias
Lowell
June 18, 2013 at 12:10 pm
starter......
SELECT TOP 10000
CustomerID = CAST(Abs(Checksum(Newid()) % 90 + 1) AS INT),
ProdID = CAST(Abs(Checksum(Newid()) % 900 + 1) AS INT)
INTO TestData
FROM sys.all_columns ac1
CROSS JOIN sys.all_columns ac2
CROSS JOIN sys.all_columns ac3
SELECT DISTINCT CustomerID
FROM TestData
SELECT DISTINCT ProdID
FROM TestData
SELECT COUNT(DISTINCT CustomerID) AS Expr1, COUNT(DISTINCT ProdID) AS Expr2
FROM TestData
________________________________________________________________
you can lead a user to data....but you cannot make them think
and remember....every day is a school day
June 18, 2013 at 12:40 pm
If you want a count of all the combinations, just multiply the count of distinct table 1 values times the count of distinct table 2 values.
declare @table1 table (value1 char(1))
declare @table2 table (value2 char(1))
insert into @table1
values ('A'),('A'),('B'),('C'),('D'),('D'),('A'),('A') -- 4 distinct values
insert into @table2
values ('X'),('Y'),('Y'),('Y'),('Z'),('1'),('2'),('3') -- 6 distinct values
select (select count(distinct value1) total1 from @table1) *
(select count(distinct value2) as total2 from @table2) as Combinations
edit: simplified final query
__________________________________________________
Against stupidity the gods themselves contend in vain. -- Friedrich Schiller
Stop, children, what's that sound? Everybody look what's going down. -- Stephen Stills
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply