How do I fix my SQL statement? - sql

I am using Microsoft SQL Server 2008. I have a table called "Tools" with the following columns [ID], [QtyOnHand], [SizeUS], [PlantID]. A typical small data sample may be something like this:
I would like to group the data by size and have a column with a sum of qty grouped by each plant that would look something like this:
I tried the following query but it's not correct.
SELECT
T.SizeUS
,(
SELECT SUM(T.QtyOnHand)
From Tools T1
WHERE T1.PlantID=1 AND T1.SizeUS=T.SizeUS
) As QtyPlant1
,(
SELECT SUM(T.QtyOnHand)
From Tools T2
WHERE T2.PlantID=2 AND T2.SizeUS=T.SizeUS
) As QtyPlant2
,(
SELECT SUM(T.QtyOnHand)
From Tools T5
WHERE T5.PlantID=5 AND T5.SizeUS=T.SizeUS
) As QtyPlant5
FROM
Tools T
GROUP BY
T.SizeUS;

Try this:
SELECT T.SizeUS,
, sum(case when T1.PlantID = 1 then 1 else 0 end) as QtyPlant1
, sum(case when T1.PlantID = 2 then 1 else 0 end) as QtyPlant2
, sum(case when T1.PlantID = 5 then 1 else 0 end) as QtyPlant5
FROM Tools T
Group By T.SizeUS

Related

SQL Server Count - Group By

I have a table contain records as per below image. I want to do a count for each status and am able to do that by selecting each type of status. Which I will needs to exec 4 query to get the result. I would like to know how can I achieve that by using single query statement? Any advices or suggestion is welcome and highly appreciated. Thanks in advance.
WITH CTE(NO,STATUS)AS
(
SELECT 1,'OPEN' UNION ALL
SELECT 2,'OPEN'UNION ALL
SELECT 3,'BILLED'UNION ALL
SELECT 4,'CANCELLED'UNION ALL
SELECT 5,'BILLING'UNION ALL
SELECT 6,'BILLED'UNION ALL
SELECT 7,'CANCELLED'UNION ALL
SELECT 8,'BILLING'UNION ALL
SELECT 9,'CONFIRM'UNION ALL
SELECT 10,'IN PROGRESS'UNION ALL
SELECT 11,'OPEN'UNION ALL
SELECT 12,'CONFIRM'
)
SELECT
SUM(CASE WHEN C.STATUS='BILLED'THEN 1 ELSE 0 END)AS BILLED,
SUM(CASE WHEN C.STATUS='BILLING'THEN 1 ELSE 0 END)AS BILLING,
SUM(CASE WHEN C.STATUS='CANCELLED'THEN 1 ELSE 0 END)AS CANCELLED,
SUM(CASE WHEN C.STATUS NOT IN ('CANCELLED','BILLING','BILLED')THEN 1 ELSE 0 END)AS UNBILL
FROM CTE AS C
CTE is an example you have provided. Please replace reference to it with reference to your table

Specific where for multiple selects

I have the following problem:
I have a table that looks something like this:
ArticleID|Group|Price
1|a|10
2|b|2
3|a|3
4|b|5
5|c|5
6|f|7
7|c|8
8|x|3
Now im trying to get a result like this:
PriceA|PriceRest
13|30
Meaning I want to sum all prices from group a in one column and the sum of everything else in another column.
Something like this doesnt work.
select
sum(Price) as PriceGroupA
sum(Price) as PriceRest
from
Table
where
Group='a'
Group<>'a'
Is there a way to achieve this functionality?
SELECT
sum(case when [Group] = 'a' then Price else 0 end) as PriceA,
sum(case when [Group] <> 'a' then Price else 0 end) as PriceRest
from
Table
Please try:
select
sum(case when [Group]='A' then Price end) PriceA,
sum(case when [Group]<>'A' then Price end) PriceRest
from
Table
SQL Fiddle Demo
You just need two sub-queries:
SELECT (SELECT SUM(PRICE)
FROM Table1
WHERE [Group] ='a') AS PriceGroupA,
(SELECT SUM(PRICE)
FROM Table1
WHERE [Group]<>'a') AS PriceRest
Demo-Fiddle

Looping in select query

I want to do something like this:
select id,
count(*) as total,
FOR temp IN SELECT DISTINCT somerow FROM mytable ORDER BY somerow LOOP
sum(case when somerow = temp then 1 else 0 end) temp,
END LOOP;
from mytable
group by id
order by id
I created working select:
select id,
count(*) as total,
sum(case when somerow = 'a' then 1 else 0 end) somerow_a,
sum(case when somerow = 'b' then 1 else 0 end) somerow_b,
sum(case when somerow = 'c' then 1 else 0 end) somerow_c,
sum(case when somerow = 'd' then 1 else 0 end) somerow_d,
sum(case when somerow = 'e' then 1 else 0 end) somerow_e,
sum(case when somerow = 'f' then 1 else 0 end) somerow_f,
sum(case when somerow = 'g' then 1 else 0 end) somerow_g,
sum(case when somerow = 'h' then 1 else 0 end) somerow_h,
sum(case when somerow = 'i' then 1 else 0 end) somerow_i,
sum(case when somerow = 'j' then 1 else 0 end) somerow_j,
sum(case when somerow = 'k' then 1 else 0 end) somerow_k
from mytable
group by id
order by id
this works, but it is 'static' - if some new value will be added to 'somerow' I will have to change sql manually to get all the values from somerow column, and that is why I'm wondering if it is possible to do something with for loop.
So what I want to get is this:
id somerow_a somerow_b ....
0 3 2 ....
1 2 10 ....
2 19 3 ....
. ... ...
. ... ...
. ... ...
So what I'd like to do is to count all the rows which has some specific letter in it and group it by id (this id isn't primary key, but it is repeating - for id there are about 80 different values possible).
http://sqlfiddle.com/#!15/18feb/2
Are arrays good for you? (SQL Fiddle)
select
id,
sum(totalcol) as total,
array_agg(somecol) as somecol,
array_agg(totalcol) as totalcol
from (
select id, somecol, count(*) as totalcol
from mytable
group by id, somecol
) s
group by id
;
id | total | somecol | totalcol
----+-------+---------+----------
1 | 6 | {b,a,c} | {2,1,3}
2 | 5 | {d,f} | {2,3}
In 9.2 it is possible to have a set of JSON objects (Fiddle)
select row_to_json(s)
from (
select
id,
sum(totalcol) as total,
array_agg(somecol) as somecol,
array_agg(totalcol) as totalcol
from (
select id, somecol, count(*) as totalcol
from mytable
group by id, somecol
) s
group by id
) s
;
row_to_json
---------------------------------------------------------------
{"id":1,"total":6,"somecol":["b","a","c"],"totalcol":[2,1,3]}
{"id":2,"total":5,"somecol":["d","f"],"totalcol":[2,3]}
In 9.3, with the addition of lateral, a single object (Fiddle)
select to_json(format('{%s}', (string_agg(j, ','))))
from (
select format('%s:%s', to_json(id), to_json(c)) as j
from
(
select
id,
sum(totalcol) as total_sum,
array_agg(somecol) as somecol_array,
array_agg(totalcol) as totalcol_array
from (
select id, somecol, count(*) as totalcol
from mytable
group by id, somecol
) s
group by id
) s
cross join lateral
(
select
total_sum as total,
somecol_array as somecol,
totalcol_array as totalcol
) c
) s
;
to_json
---------------------------------------------------------------------------------------------------------------------------------------
"{1:{\"total\":6,\"somecol\":[\"b\",\"a\",\"c\"],\"totalcol\":[2,1,3]},2:{\"total\":5,\"somecol\":[\"d\",\"f\"],\"totalcol\":[2,3]}}"
In 9.2 it is also possible to have a single object in a more convoluted way using subqueries in instead of lateral
SQL is very rigid about the return type. It demands to know what to return beforehand.
For a completely dynamic number of resulting values, you can only use arrays like #Clodoaldo posted. Effectively a static return type, you do not get individual columns for each value.
If you know the number of columns at call time ("semi-dynamic"), you can create a function taking (and returning) polymorphic parameters. Closely related answer with lots of details:
Dynamic alternative to pivot with CASE and GROUP BY
(You also find a related answer with arrays from #Clodoaldo there.)
Your remaining option is to use two round-trips to the server. The first to determine the the actual query with the actual return type. The second to execute the query based on the first call.
Else, you have to go with a static query. While doing that, I see two nicer options for what you have right now:
1. Simpler expression
select id
, count(*) AS total
, count(somecol = 'a' OR NULL) AS somerow_a
, count(somecol = 'b' OR NULL) AS somerow_b
, ...
from mytable
group by id
order by id;
How does it work?
Compute percents from SUM() in the same SELECT sql query
SQL Fiddle.
2. crosstab()
crosstab() is more complex at first, but written in C, optimized for the task and shorter for long lists. You need the additional module tablefunc installed. Read the basics here if you are not familiar:
PostgreSQL Crosstab Query
SELECT * FROM crosstab(
$$
SELECT id
, count(*) OVER (PARTITION BY id)::int AS total
, somecol
, count(*)::int AS ct -- casting to int, don't think you need bigint?
FROM mytable
GROUP BY 1,3
ORDER BY 1,3
$$
,
$$SELECT unnest('{a,b,c,d}'::text[])$$
) AS f (id int, total int, a int, b int, c int, d int);

SQL Server Pivoting based off of a column to be delimited

I'm using SQL Server Management Studio and I have a table of survey results for project managers and I'm aggregating by question/score at the project manager RepID level:
SELECT Lower(A.RepID) as 'HHRepID'
, YEAR(A.ProjectEndDate) AS 'Year'
, MONTH(A.ProjectEndDate) AS 'Month'
, DATENAME(mm,A.ProjectEndDate) AS 'MonthName'
, SUM(CASE WHEN A.SatisfactionWithCommunication >= 4 THEN 1 ELSE 0 END) as 'AgreeStronglyAgreeCommunicationCount'
, COUNT(A.SatisfactionWithCommunication) as 'CommunicationCount'
, SUM(CASE WHEN A.InteractionConnectionWithClient >= 4 THEN 1 ELSE 0 END) as 'AgreeStronglyAgreeInteractionCount'
, COUNT(A.InteractionConnectionWithClient) as 'InteractionCount'
, SUM(CASE WHEN A.OverallSatisfactionWithEngagement >= 4 THEN 1 ELSE 0 END) as 'AgreeStronglyAgreeOverallSatisfactionCount'
, COUNT(A.OverallSatisfactionWithEngagement) as 'OverallSatisfactionCount'
, COUNT(A.ResponseID) as 'SurveysReturned'
, 'SalesOps' as 'Grouping'
FROM
SurveyData.dbo.SalesSurvey as A with(nolock)
WHERE
A.ResponseID IS NOT NULL AND A.IsExcludedFromReporting IS NULL
GROUP BY
YEAR(A.ProjectEndDate), MONTH(A.ProjectEndDate), DATENAME(mm,A.ProjectEndDate), A.RepID
ORDER BY
A.RepID
The output would look something like this:
Everything is great. Here's the problem. For each response for a project manager, there could be multiple Project Assistants. The project assistants for each project are aggregated (separated by ;) in one column:
What I need to do is pivot/delimit these results so each projectassistantID will be 1 row with the same grouped data as if it was a project manager. So for example, let's say that that row from the first screenshot had (HHRepID = jdoe) had 2 project assistants to it (call them Michael Matthews and Sarah Boyd): mmathews; sboyd. Via pivot/delimit, the output of the 2nd query would look like this:
In the actual table, it's just 1 record. But b/c there're multiple names in the ProjectAssistantID column, I need to pivot/delimit those out and essentially get the same results for each instance, just with ProjectAssistants rather than Project Managers.
I've been able to find some stuff on pivoting but this is pivoting based on delimiting values which adds an extra layer of complexity. It's entirely possible that there could be only 1 project assistant per project or as many as 6.
You can find several string split functions when you google for that, I will just assume this one which returns a table with one column named Item.
Then you can use cross apply as follows:
SELECT assist.Item as 'HHRepID'
, YEAR(A.ProjectEndDate) AS 'Year'
, MONTH(A.ProjectEndDate) AS 'Month'
, DATENAME(mm,A.ProjectEndDate) AS 'MonthName'
, SUM(CASE WHEN A.SatisfactionWithCommunication >= 4 THEN 1 ELSE 0 END) as 'AgreeStronglyAgreeCommunicationCount'
, COUNT(A.SatisfactionWithCommunication) as 'CommunicationCount'
, SUM(CASE WHEN A.InteractionConnectionWithClient >= 4 THEN 1 ELSE 0 END) as 'AgreeStronglyAgreeInteractionCount'
, COUNT(A.InteractionConnectionWithClient) as 'InteractionCount'
, SUM(CASE WHEN A.OverallSatisfactionWithEngagement >= 4 THEN 1 ELSE 0 END) as 'AgreeStronglyAgreeOverallSatisfactionCount'
, COUNT(A.OverallSatisfactionWithEngagement) as 'OverallSatisfactionCount'
, COUNT(A.ResponseID) as 'SurveysReturned'
, 'SalesOps' as 'Grouping'
FROM
SurveyData.dbo.SalesSurvey as A with(nolock)
CROSS APPLY Split(Lower(A.RepID), ';') AS assist
WHERE
A.ResponseID IS NOT NULL AND A.IsExcludedFromReporting IS NULL
GROUP BY
YEAR(A.ProjectEndDate), MONTH(A.ProjectEndDate), DATENAME(mm,A.ProjectEndDate), assist.Item
ORDER BY
assist.Item
For a strictly sql solution, you could use recursive cte to get your names split and then join it back to you query..
Try the below query
DECLARE #col varchar(20)='a;b;c;g;y;u;i;o;p;';
WITH CTE as
(
SELECT SUBSTRING(#COL,CHARINDEX(';',#COL)+1, LEN(#COL)-CHARINDEX(';', #COL)) col
,SUBSTRING(#COL,0, CHARINDEX(';',#COL)) Split_Names
, 1 i
union ALL
SELECT SUBSTRING(COL,CHARINDEX(';',COL)+1, LEN(COL)-CHARINDEX(';', COL)) col
,SUBSTRING(COL,0, CHARINDEX(';',COL)) Split_Names
, i+1
from CTE
WHERE CHARINDEX(';', col)>1
)
SELECT * FROM CTE
You will need to use your column in place of #col and change the code to refer to your table in the first union statement.
Hope this helps...
So you would do something like this...
WITH ProjectAssistants as
(
SELECT SUBSTRING(PROJECTASSISTANTID,CHARINDEX(';',PROJECTASSISTANTID)+1, LEN(PROJECTASSISTANTID)-CHARINDEX(';', PROJECTASSISTANTID)) col
,SUBSTRING(PROJECTASSISTANTID,0, CHARINDEX(';',PROJECTASSISTANTID)) Assistnames_Names
, ProjectManagerID
FROM YOUR_PROJECT_ASSISTANT_TABLE_NAME
union ALL
SELECT SUBSTRING(COL,CHARINDEX(';',COL)+1, LEN(COL)-CHARINDEX(';', COL)) col
,SUBSTRING(COL,0, CHARINDEX(';',COL)) Assistnames_Names
, ProjectManagerID
from ProjectAssistants
WHERE CHARINDEX(';', col)>1
)
SELECT Lower(A.RepID) as 'HHRepID'
, YEAR(A.ProjectEndDate) AS 'Year'
, MONTH(A.ProjectEndDate) AS 'Month'
, DATENAME(mm,A.ProjectEndDate) AS 'MonthName'
, SUM(CASE WHEN A.SatisfactionWithCommunication >= 4 THEN 1 ELSE 0 END) as 'AgreeStronglyAgreeCommunicationCount'
, COUNT(A.SatisfactionWithCommunication) as 'CommunicationCount'
, SUM(CASE WHEN A.InteractionConnectionWithClient >= 4 THEN 1 ELSE 0 END) as 'AgreeStronglyAgreeInteractionCount'
, COUNT(A.InteractionConnectionWithClient) as 'InteractionCount'
, SUM(CASE WHEN A.OverallSatisfactionWithEngagement >= 4 THEN 1 ELSE 0 END) as 'AgreeStronglyAgreeOverallSatisfactionCount'
, COUNT(A.OverallSatisfactionWithEngagement) as 'OverallSatisfactionCount'
, COUNT(A.ResponseID) as 'SurveysReturned'
, 'SalesOps' as 'Grouping'
FROM
SurveyData.dbo.SalesSurvey as A with(nolock)
LEFT JOIN ProjectAssistants as B
ON A.ProjectManagerID=B.ProjectManagerID
WHERE
A.ResponseID IS NOT NULL AND A.IsExcludedFromReporting IS NULL
GROUP BY
YEAR(A.ProjectEndDate), MONTH(A.ProjectEndDate), DATENAME(mm,A.ProjectEndDate), A.RepID
ORDER BY
A.RepID
Assumptions:
Your Surveydata table has a ProjectManagerid column
Left Join-ed the ProjectManager CTE considering you still want to show data when there arent any assistants.

sql select display row data as columns

I have a sql select query that extracts result as:
login_count login_type
2000 iPhone
7000 browser
But i want the result as:
iphone_login browser_login
2000 7000
i.e. i want to extract row1-col1 as col1 and row2-col2 as col2 using a select query.
My original query is
select count(login_count), login_type from log_table group by login_type;
Thanks,
Gaurav
Try this:
SELECT
SUM( IF(login_type = 'iPhone', 1, 0) ) AS iphone_login,
SUM( IF(login_type = 'browser', 1, 0) ) AS browser_login
FROM log_table
Here is another option that works in MySQL and in other dbms as well.
select sum(case when login_type = 'iPhone' then 1 else 0 end) as iphone_login
,sum(case when login_type = 'browser' then 1 else 0 end) as browser_login
from log_table