Pivot in SQL without Aggregate function - sql

I have a scenario Where I have a table like
Table View
and What Output I want is

If your argument is "I will only ever have one value or no values, therefore I don't want an aggregate", realise that there are several aggregates that, if they're only passed a single value to aggregate, will return that value back as their result. MIN and MAX come to mind. SUM also works for numeric data.
Therefore the solution to specifying a PIVOT without an aggregate is instead to specify such a "pass through" aggregate here.
Basically, PIVOT internally works a lot the same as GROUP BY. Except the grouping columns are all columns in the current result set other than the column mentioned in the aggregate part of the PIVOT specification. And just as with the rules for the SELECT clause when GROUP BY is used1, every column either needs to be a grouping column or contained in an aggregate.
1Grumble, grumble, older mysql grumble. Although the defaults are more sensible from 5.7.5 up.

Try this:
Demo
with cte1 as
(
select 'Web' as platformname,'abc' as productname,'A' as grade
union all
select 'Web' ,'cde' ,'B'
union all
select 'IOS' ,'xyz' ,'C'
union all
select 'MAX' ,'cde' ,'D'
)
select productname,[Web], [IOS], [Android],[Universal],[Mac],[Win32]
from cte1 t
pivot
(
max(grade)
for platformname in ([Web], [IOS], [Android],[Universal],[Mac],[Win32])
) p

You can "pivot" such data using joins:
select p.productname,
t_win32.grade as win32,
t_universal.grade as universal,
. . .
from products p left join -- assume you have such a table
t t_win32
on t_win32.product_name = p.productname and t_win32.platform = 'Win32' left join
t t_universal
on t_universal.product_name = p.productname and t_universal.platform = 'Universal' left join
. . .
If you don't have a table products, use a derived table instead:
from (select distinct product_name from t) p left join
. . .

Related

How to use unpivot operator to combine rows and columns?

I need to group customers by GroupName. Customers can be duplicated on each GroupName. Each GroupName has a unique number called "GroupCode" in table OCQG. Customer table (OCRD) has separate column for Each GroupCode. As an example, C-0001 customer can have more group names.We can identify GroupCodes for each customer by see Group1,...,Group64 column values.(If this value = Y).Table structure as follows.Please help me.
I tried following query.But it didn't work.
SELECT p.CardCode, REPLACE(p.QryGroup,'GROUP','') groupcode, ocqg.GroupName
FROM ocrd UNPIVOT
( value
FOR groupcode IN ([QryGroup1],[QryGroup2],[QryGroup3])
) as p,
ocqg
WHERE value = 'Y' and
ocqg.GroupCode = REPLACE(p.groupcode,'GROUP','')
order by p.CardCode
Table Structure as follows,
I recommend using APPLY for this purpose:
SELECT ocrd.CardCode, v.groupcode, ocqg.GroupName
FROM ocrd CROSS APPLY
(VALUES (1, QryGroup1),
(2, QryGroup2),
(3, QryGroup3),
. . .
) v(GroupCode, Value) JOIN
ocqg
ON ocqg.GroupCode = v.GroupCode
WHERE v.value = 'Y'
ORDER BY p.CardCode;
UNPIVOT is bespoke syntax for SQL Server and Oracle that does one thing.
On the other hand, APPLY implements "lateral join"s.' These are very powerful -- much more powerful than UNPIVOT -- and supported by more databases.

Is there a way to use DISTINCT and COUNT(*) together to bulletproof your code against DUPLICATE entries?

I got help with a function yesterday to correctly get the count of multiple items in a column based on multiple criteria/columns. However, if there is a way to get the DISTINCT count of all the entries in the table based on aggregated GROUP BY statement.
SELECT TIME = ap.day,
acms.tenantId,
acms.CallingService,
policyList = ltrim(sp.value),
policyInstanceList = ltrim(dp.value),
COUNT(*) AS DISTINCTCount
FROM dbo.acms_data acms
CROSS APPLY string_split(acms.policyList, ',') sp
CROSS APPLY string_split(acms.policyInstanceList, ',') dp
CROSS APPLY (select day = convert(date, acms.[Time])) ap
GROUP BY ap.day, acms.tenantId, sp.value, dp.value, acms.CallingService
I would just like to know if there would be a way to see if there is a workaround for using DISTINCT and Count(*) together and whether or not it would affect my results to make this algorithm potentially invulnerable to duplicate entries.
The reason why I have to use COUNT(*) is because I am aggregating based on every column in the table not just a specific column or multiple.
We can use DISTINCT with COUNT together like this example.
USE AdventureWorks2012
GO
-- This query shows 290 JobTitle
SELECT COUNT(JobTitle) Total_JobTitle
FROM [HumanResources].[Employee]
GO
-- This query shows only 67 JobTitle
SELECT COUNT( DISTINCT JobTitle) Total_Distinct_JobTitle
FROM [HumanResources].[Employee]
GO

Count query giving wrong column name error

select COUNT(analysed) from Results where analysed="True"
I want to display count of rows in which analysed value is true.
However, my query gives the error: "The multi-part identifier "Results.runId" could not be bound.".
This is the actual query:
select ((SELECT COUNT(*) AS 'Count'
FROM Results
WHERE Analysed = 'True')/failCount) as PercentAnalysed
from Runs
where Runs.runId=Analysed.runId
My table schema is:
The value I want for a particular runId is: (the number of entries where analysed=true)/failCount
EDIT : How to merge these two queries?
i) select runId,Runs.prodId,prodDate,prodName,buildNumber,totalCount as TotalTestCases,(passCount*100)/(passCount+failCount) as PassPercent,
passCount,failCount,runOwner from Runs,Product where Runs.prodId=Product.prodId
ii) select (cast(counts.Count as decimal(10,4)) / cast(failCount as decimal(10,4))) as PercentAnalysed
from Runs
inner join
(
SELECT COUNT(*) AS 'Count', runId
FROM Results
WHERE Analysed = 'True'
GROUP BY runId
) counts
on counts.runId = Runs.runId
I tried this :
select runId,Runs.prodId,prodDate,prodName,buildNumber,totalCount as TotalTestCases,(passCount*100)/(passCount+failCount) as PassPercent,
passCount,failCount,runOwner,counts.runId,(cast(counts.Count as decimal(10,4)) / cast(failCount as decimal(10,4))) as PercentAnalysed
from Runs,Product
inner join
(
SELECT COUNT(*) AS 'Count', runId
FROM Results
WHERE Analysed = 'True'
GROUP BY runId
) counts
on counts.runId = Runs.runId
where Runs.prodId=Product.prodId
but it gives error.
Your problems are arising from improper joining of tables. You need information from both Runs and Results, but they aren't combined properly in your query. You have the right idea with a nested subquery, but it's in the wrong spot. You're also referencing the Analysed table in the outer where clause, but it hasn't been included in the from clause.
Try this instead:
select (cast(counts.Count as decimal(10,4)) / cast(failCount as decimal(10,4))) as PercentAnalysed
from Runs
inner join
(
SELECT COUNT(*) AS 'Count', runId
FROM Results
WHERE Analysed = 'True'
GROUP BY runId
) counts
on counts.runId = Runs.runId
I've set this up as an inner join to eliminate any runs which don't have analysed results; you can change it to a left join if you want those rows, but will need to add code to handle the null case. I've also added casts to the two numbers, because otherwise the query will perform integer division and truncate any fractional amounts.
I'd try the following query:
SELECT COUNT(*) AS 'Count'
FROM Results
WHERE Analysed = 'True'
This will count all of your rows where Analysed is 'True'. This should work if the datatype of your Analysed column is either BIT (Boolean) or STRING(VARCHAR, NVARCHAR).
Use CASE in Count
SELECT COUNT(CASE WHEN analysed='True' THEN analysed END) [COUNT]
FROM Results
Click here to view result
select COUNT(*) from Results where analysed="True"

Show %s in Access 2010 Crosstab query instead of just counts

I have the following two queries that build/feed into the third query. My goal is to have a crosstab query of [MCOs] down the left and possible responses/values for [DrpDown] across the top with the values shown as percentages of the total for each [MCO] (so % of row total).
What I have works, but I want to know if I can do it all in one query.
SELECT tblMCOs.MCOs, tblMCOs.DrpDwn, Count(tblMCOs.ID) AS CountOfID
FROM tblMCOs
GROUP BY tblMCOs.MCOs, tblMCOs.DrpDwn;
SELECT tblMCOs.MCOs, Count(tblMCOs.DrpDwn) AS CountOfDrpDwn
FROM tblMCOs
GROUP BY tblMCOs.MCOs;
TRANSFORM Sum(Round([qryMCODrpDwnCt]![CountOfID]/[qryMCOCtDrpDwn]!
[CountOfDrpDwn],4)*100) AS PCT
SELECT qryMCODrpDwnCt.MCOs
FROM qryMCODrpDwnCt INNER JOIN qryMCOCtDrpDwn ON qryMCODrpDwnCt.MCOs =
qryMCOCtDrpDwn.MCOs
GROUP BY qryMCODrpDwnCt.MCOs
PIVOT qryMCODrpDwnCt.DrpDwn;
Thanks in advance for your help.
What I have works, but I want to know if I can do it all in one query.
Crosstab queries can be a bit fussy, but simply inserting the SQL code as subqueries should work:
TRANSFORM Sum(Round([sqMCODrpDwnCt]![CountOfID]/[sqMCOCtDrpDwn]![CountOfDrpDwn],4)*100) AS PCT
SELECT sqMCODrpDwnCt.MCOs
FROM
(
SELECT tblMCOs.MCOs, tblMCOs.DrpDwn, Count(tblMCOs.ID) AS CountOfID
FROM tblMCOs
GROUP BY tblMCOs.MCOs, tblMCOs.DrpDwn
) AS sqMCODrpDwnCt
INNER JOIN
(
SELECT tblMCOs.MCOs, Count(tblMCOs.DrpDwn) AS CountOfDrpDwn
FROM tblMCOs
GROUP BY tblMCOs.MCOs
) AS sqMCOCtDrpDwn
ON sqMCODrpDwnCt.MCOs = sqMCOCtDrpDwn.MCOs
GROUP BY sqMCODrpDwnCt.MCOs
PIVOT sqMCODrpDwnCt.DrpDwn

differentiate rows in a union table

I m selecting data from two different tables with no matching columns using this sql query
select * from (SELECT s.shout_id, s.user_id, s.time FROM shouts s
union all
select v.post_id, v.sender_user_id, v.time from void_post v)
as derived_table order by time desc;
Now is there any other way or with this sql statement only can i
differentiate the data from the two tables.
I was thinking of a dummy row that can be created at run-time(in the select statement only ) which would flag the row from the either tables.
As there is no way i can differentiate the shout_id that is thrown in the unioned table is
shout_id from the shout table or from the void_post table.
Thanks
Pradyut
You can just include an extra column in each select (I'd suggest a BIT)
select * from
(SELECT s.shout_id, s.user_id, s.time, 1 AS FromShouts FROM shouts s
union all
select v.post_id, v.sender_user_id, v.time, 0 AS FromShouts from void_post v)
as derived_table order by time desc;
Sure, just add a new field in your select statement called something like source with a different constant value for each source.
SELECT s.shout_id, s.user_id, s.time, 'shouts' as source FROM shouts s
UNION ALL
SELECT v.post_id, v.sender_user_id, v.time, 'void_post' as source FROM void_post v
A dummy variable is a nice way to do it. There isn't much overhead in the grand scheme of things.
p.s., the dummy variable represents a column and not a row.