Pivot Customer Policies data - sql-server

Write a query to create a pivot table to display the number of customers taken policies with policy_value 250000,75000,45000. Specify the name of the first column in the pivot table as 'customer_count' with literal value as customerCount. Use: PIVOT
As a solution I have used the following code.
select id as customer_count, [250000], [75000], [45000]
from
(
select * from customer_policy
)
PIVOT
(count(id) FOR policy_value IN [250000], [75000], [45000])
GO
But getting error as Incorrect syntax near the keyword 'PIVOT'.
EDIT
Output is required in the below format

These are typographical error really. You have several errors in the above SQL.
You don't alias your subquery
You are missing parenthesis (()) around your IN clause
You don't alias your pivot
ID doesn't exist in the returned columns for your pivot, so needs to be removed
If you fix this, you get a valid query:
SELECT [250000],
[75000],
[45000]
FROM (SELECT * FROM customer_policy) cp
PIVOT (COUNT(id)
FOR policy_value IN ([250000], [75000], [45000])) p;
Though, in true, you don't actually need the subquery:
SELECT [250000],
[75000],
[45000]
FROM customer_policy cp
PIVOT (COUNT(id)
FOR policy_value IN ([250000], [75000], [45000])) p;
You may need other columns in your SELECT, as you use a *, I don't know what other columns you want to expose.

Below is the answer to the question
SELECT 'customerCount' AS customer_count,
[250000],
[75000],
[45000]
FROM (SELECT id, policy_value FROM customer_policy) cp
PIVOT (COUNT(id)
FOR policy_value IN ([250000], [75000], [45000])) p;

Related

Count all max number value in difference tables sql

I got an error when I tried to solve this problem. First I need to count all values of 2 tables then I need in where condition get all max values.
My code:
Select *
FROM (
select Operator.OperatoriausPavadinimas,
(
select count(*)
from Plan
where Plan.operatoriausID= Operator.operatoriausID
) as NumberOFPlans
from Operator
)a
where a.NumberOFPlans= Max(a.NumberOFPlans)
I get this error
Msg 147, Level 15, State 1, Line 19
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
I don't know how to solve this.
I need get this http://prntscr.com/p700w9
Update 1
Plan table contains of http://prntscr.com/p7055l values and
Operator table contains of http://prntscr.com/p705k0 values.
Are you looking for... an aggregate query that joins both tables and returns the record that has the maximum count?
I suspect that this might phrase as follows:
SELECT TOP(1) o.OperatoriausPavadinimas, COUNT(*)
FROM Operatorius o
INNER JOIN Planas p ON p.operatoriausID = o.operatoriausID
GROUP BY o.OperatoriausPavadinimas
ORDER BY COUNT(*) DESC
If you want to allow ties, you can use TOP(1) WITH TIES.
You can use top with ties. Your query is a bit hard to follow, but I think you want:
select top (1) with ties o.OperatoriausPavadinimas, count(*)
from plan p join
operator o
on p.operatoriausID = o.operatoriausID
group by o.OperatoriausPavadinimas
order by count(*) desc;

SQL Server reference fields in derived table with unions

I'm having a bit of an issue with some derived tables that I hope someone will be able to help with. What I've got is 2 derived tables inside a select statement that then uses a pivot to display the results horizontally rather than vertically.
What I've got so far is:
SELECT * FROM(
SELECT SUM(Value) AS TotDays, ClassId FROM MainTable GROUP BY ClassId)
Union All
SELECT SUM(NumDays) As TotDays, ClassId FROM (
SELECT CASE WHEN COUNT(SiteId) > 0 THEN 1 ELSE 0 END AS NumDays
FROM Table2 GROUP BY ClassId ) as SUB
) AS a
PIVOT (SUM(TotDays) FROM ClassId
IN ([12],[13],[14],[15]
What I'm trying to do is reference the individual columns rather than using SELECT *, but I don't know how to do it. I can make it work without if I drop everything from the union onwards, but when I put the union in it doesn't work and I have to use SELECT *.
Anyone got any ideas on what's going wrong?
Thanks
Alex
You have a couple of errors on your query. For example, your UNION ALL has sets with a different number of columns, and you have other syntax errors. Try this way:
SELECT [12],[13],[14],[15]
FROM ( SELECT SUM(Value) AS TotDays, ClassId
FROM MainTable
GROUP BY ClassId
UNION ALL
SELECT SUM(NumDays) As TotDays, ClassId
FROM ( SELECT CASE WHEN COUNT(SiteId) > 0 THEN 1 ELSE 0 END NumDays,
ClassId
FROM Table2
GROUP BY ClassId) as SUB
) AS a
PIVOT (SUM(TotDays) FROM ClassId IN ([12],[13],[14],[15])) AS PT

TSQL self join to get results

I run the following query
Select * From
(
Select
GUID,
MFG_CODE,
STK_NAME,
parentid,
masteritem,
ROW_NUMBER() over(order by guid) r
From Fstock Where MasterItem=1 OR isNull(parentID, '')=''
) a
Where r between 4716 And 4716
And I get following results
GUID MFG_CODE parentid masteritem r
31955 369553 0 1 4717
As you can see GUID 31955 is actually a parentITEM & I need to bring in all the children of this parent item within the same query.
For example if I do:
Select * From Fstock where parentID = 31955
It returns 3 children of it
GUID
31956
31957
31958
So is there a way to combine these two queries together, I only want to return fixed amount of rows using row_number() function, however those returned rows sometimes contain a Parent ITem, I would like to return the children for those parent items as well within same query.
Performance is very important for me.
--- EDIT ----
I got it to work with following query, does anyone have other ideas?
With CTE
As
(
Select
GUID,
Manufacturer,
SELL_PRICE,
MFG_CODE,
parentid,
masteritem,
ROW_NUMBER() over(order by GUID) r
From Fstock Where MasterItem=1 OR isNull(parentID, '')=''
)
Select A.*,F.parentID From
(
Select * From CTE
Where r between 4717 And 6000
) A
Left join Fstock F on F.parentID = A.GUID
Order by A.r
This is crude and untested, but I believe you're looking for a recursive Common Table Expression (CTE) that will combine the parent-child relationships for you. Now, natively, this does not integrate any row limitations you mentioned in terms of returning a "fixed number of rows," which I was not precisely sure how to interpret, but the basic query below should be a start for you.
With Products(GUID, MFG_CODE,STK_NAME, parentid,masteritem)
as
(
Select GUID,MFG_CODE,STK_NAME,parentid,masteritem
from fstock
where masteritem=1 OR isNull(parentID, '')=''
Union all
Select f.GUID,f.MFG_CODE,f.STK_NAME,f.parentid,f.masteritem
from fstock f
inner join products g
on f.parentid=g.guid
)

How to nest CTE properly

This question was asked few other times, but I still did not manage to sort out the right answer or proper way to do this:
...
;WITH CTE AS
(
SELECT * FROM ...
)
SELECT *, [dbo].[udf_BetaInv](A, B, C, D) AS 'Loss'
FROM CTE
WHERE (Loss >= #MinRetention)
This does not work and I cannot create the stored procedure, clearly I cannot use Loss in the WHERE because does not exist in that scope.
I would like to use another CTE to wrap this one so I can put the WHERE on the outer one but not does not seem to work, tried this:
;WITH CTE AS
(
SELECT * FROM ...
)
SELECT *, [dbo].[udf_BetaInv(A, B, C, D) AS 'Loss'
FROM CTE,
RESULTS AS
(SELECT * FROM CTE)
SELECT *
FROM RESULTS
WHERE (Loss >= #MinRetention)
But it does not compile in SQL Server, I get an error that a '(' is misplaces many rows above but has nothing to do, if I remove the second CTE it works fine.
I only want to avoid code duplication, not want to call my [udf_BetaInv] twice in the select and also in the where.
You have an intermediate SELECT that you should not have. This should work:
;WITH CTE AS
(
SELECT * FROM ...
),
RESULTS AS
(
SELECT *, [dbo].[udf_BetaInv(A, B, C, D) AS 'Loss'
FROM CTE
)
SELECT *
FROM RESULTS
WHERE (Loss >= #MinRetention)
Obviously the problem with the first query is that 'Loss' is just a column alias and can't be used in a WHERE clause. You're right that using it in a CTE would avoid duplicating the expression. Here's how you'd do that;
WITH CTE AS
(
SELECT * FROM ...
),
CteWithLoss AS (
SELECT *, [dbo].[udf_BetaInv](A, B, C, D) AS 'Loss'
FROM CTE
)
SELECT *
FROM CteWithLoss
WHERE (Loss >= #MinRetention);
On a side note: See if you can break the habit of starting your CTE definitions with ;WITH and instead get into the habit of ending all your SQL statements with a semi-colon. It's more readable and better practice.
Below is the example of nested CTE.
with cte_data as
(
Select * from [HumanResources].[Department]
),cte_data1 as
(
Select * from cte_data
)
select * from cte_data1

what does adding ranked to a mysql query do?

What does adding ranked to a mysql query do?
I'm trying code from this post
SELECT * FROM ( SELECT #row := #row +1 AS rownum, [column name] FROM ( SELECT #row :=0) r, [table name] ) ranked WHERE rownum % [n] = 1
"ranked" is an alias that you're giving to your sub-select. You're just omitting the "AS" keyword, which is allowed in MySQL.
Example: SELECT name from MyTable AS table1
Nothing, apparently, as "ranked" isn't a MySQL keyword that I can find. Did you possibly mean "ordered by"?

Resources