Wrong Result in SUM() - sql

SQL Server 2000 - 4 tables, 3 columns each. Personal ID (COTA), User (Telegestionador), and an amount-of-work value.
Tables are: Contactados, NC, FQ, OT
Example of one of them.
XAV045 QUIPILDORY 26
XAV045 QUIPILDORY 29
XAV045 QUIPILDORY 21
XAV045 QUIPILDORY 39
XAV052 LOPEZRA 29
XAV052 LOPEZRA 39
XAV052 LOPEZRA 24
XAV052 LOPEZRA 36
What I need is. A result-view with ID, USER and then the fields with the sum of the amount of work grouped by personal id/user. (there are 4 tables, so in the final view I should have 6 columns)
So, first row should be
XAV045,QUIPILDORY, 115, X, Y, Z
Being X, Y, Z the results of SUM() from the other 3 tables.
First try is this:
SELECT
dbo.Contactados.COTA, dbo.Contactados.telegestionador,
SUM(dbo.Contactados.Total) AS Total,
SUM(dbo.OT.Total) AS [Cont-Der],
SUM(dbo.FQ.FQ) AS Cerrados,
SUM(dbo.NC.Total) AS NC
FROM
dbo.Contactados
LEFT OUTER JOIN
dbo.OT ON dbo.Contactados.COTA = dbo.OT.COTA AND dbo.Contactados.telegestionador = dbo.OT.telegestionador AND dbo.Contactados.FGfin = dbo.OT.FGfin
LEFT OUTER JOIN
dbo.FQ ON dbo.Contactados.COTA = dbo.FQ.COTA AND dbo.Contactados.telegestionador = dbo.FQ.telegestionador AND dbo.Contactados.FGfin = dbo.FQ.FGfin
LEFT OUTER JOIN
dbo.NC ON dbo.Contactados.COTA = dbo.NC.COTA AND dbo.Contactados.telegestionador = dbo.NC.telegestionador AND dbo.Contactados.FGfin = dbo.NC.FGfin
GROUP BY
dbo.Contactados.telegestionador, dbo.Contactados.COTA
It throws wrong results, I know GROUP BY groups the results, not the table rows individually. But I can't find the proper way to do so.
Any help?

Assuming that all four tables have identical datatypes for the four columns, you can use a union all to list all values, and then sum those as part of a subquery:
SELECT
COTA
,Telegestionador
,SUM(CASE WHEN table_name = 'Contactados' THEN work_value ELSE 0 END) AS Contactados_sum
,SUM(CASE WHEN table_name = 'NC' THEN work_value ELSE 0 END) AS nc_sum
,SUM(CASE WHEN table_name = 'FQ' THEN work_value ELSE 0 END) AS fq_sum
,SUM(CASE WHEN table_name = 'QT' THEN work_value ELSE 0 END) AS qt_sum
FROM
(
SELECT
COTA
,Telegestionador
,work_value
,'Contactados' as table_name
FROM Contactados
UNION ALL
SELECT
COTA
,Telegestionador
,work_value
,'NC' as table_name
FROM NC
UNION ALL
SELECT
COTA
,Telegestionador
,work_value
,'FQ' as table_name
FROM FQ
UNION ALL
SELECT
COTA
,Telegestionador
,work_value
,'QT' as table_name
FROM QT
) summary
GROUP BY
COTA
,Telegestionador

Related

aliasing pivot column

i am trying to alias the pivot column to scenario1, scenario2, scenario3 instead of 1,2,3. I am getting error.
select *
from (select *
from (select s.campaign_id campaign_id, s.scenario_index scenario_index
from scenario s, campaign c where s.campaign_id = c.campaign_id)
pivot (max(scenario_index)for scenario_index in (1,2,3))
)a
thank you, aggregation gives the result with alias now. The requirement i have is to combine these columns with another query which is
select CASE WHEN AWARD_TYPE = 0 THEN award_rate||' points'
when AWARD_TYPE = 1 then Award_rate||' %'
when award_type=2 then RATIO_POINTS||' points per '||RATIO_MON_UNIT||' AED' End
from points_rule p
where c.pt_basic_rule_id = p.point_rule_id ) as pool_awards,
this query comes as a column and then the scenario1, 2,3 should come as 3 columns with the value of the pool_award based on the campaign_id
Just use conditional aggregation:
select s.campaign_id,
max(case when scenario_index = 1 then 1 end) as scenario1,
max(case when scenario_index = 2 then 1 end) as scenario2,
max(case when scenario_index = 3 then 1 end) as scenario3
from scenario s join
campaign c
on s.campaign_id = c.campaign_id
group by campaign_id;
You can use an alias in IN clause of the PIVOT as follows:
select *
from (select *
from (select s.campaign_id campaign_id, s.scenario_index scenario_index
from scenario s, campaign c where s.campaign_id = c.campaign_id)
pivot (max(scenario_index)for scenario_index in (1 as scenario1,2 as scenario2,3 as scenario3))
)a

How to SUM values from two columns

I have the following information in a table
Load Number Origin Destination
1 AR TX
2 AR AL
3 TX MS
4 WA AR
I need help with a SQL statement that will produce the follow results
State Origin Destination
AR 2 1
TX 1 1
WA 1
MS 1
I have tried countless types of SELECT statements with various types of COUNTS in them and GROUP BY's at the end but I can't get the results I'm looking for. Any help is greatly appreciated.
How about:
select state,
sum(origin) origin,
sum(destination) destination
from (select origin as state,
0 as destination,
1 as origin
from my_table
union all
select destination,
1,
0
from my_table)
group by state
You can first build a inner query to select all the distinct states from Origin and Destination columns. Then you can join it back to the main table and do a conditional aggregation.
Demo
select x.state,
sum(case when x.state = t.Origin then 1 end),
sum(case when x.state = t.Destination then 1 end)
from tablename t
join (
select Origin as State
from tablename
union
select Destination
from tablename ) x
on t.Origin = x.state or t.Destination = x.state
group by x.state

counting records on the same table with different values possibly none sql server 2008

I have a inventory table with a condition i.e. new, used, other, and i am query a small set of this data, and there is a possibility that all the record set contains only 1 or all the conditions. I tried using a case statement, but if one of the conditions isn't found nothing for that condition returned, and I need it to return 0
This is what I've tried so far:
select(
case
when new_used = 'N' then 'new'
when new_used = 'U' then 'used'
when new_used = 'O' then 'other'
end
)as conditions,
count(*) as count
from myDB
where something = something
group by(
case
when New_Used = 'N' then 'new'
when New_Used = 'U' then 'used'
when New_Used = 'O' then 'other'
end
)
This returns the data like:
conditions | count
------------------
new 10
used 45
I am trying to get the data to return like the following:
conditions | count
------------------
new | 10
used | 45
other | 0
Thanks in advance
;WITH constants(letter,word) AS
(
SELECT l,w FROM (VALUES('N','new'),('U','used'),('O','other')) AS x(l,w)
)
SELECT
conditions = c.word,
[count] = COUNT(x.new_used)
FROM constants AS c
LEFT OUTER JOIN dbo.myDB AS x
ON c.letter = x.new_used
AND something = something
GROUP BY c.word;
try this -
DECLARE #t TABLE (new_used CHAR(1))
INSERT INTO #t (new_used)
SELECT t = 'N'
UNION ALL
SELECT 'N'
UNION ALL
SELECT 'U'
SELECT conditions, ISNULL(r.cnt, 0) AS [count]
FROM (
VALUES('U', 'used'), ('N', 'new'), ('O', 'other')
) t(c, conditions)
LEFT JOIN (
SELECT new_used, COUNT(1) AS cnt
FROM #t
--WHERE something = something
GROUP BY new_used
) r ON r.new_used = t.c
in output -
new 2
used 1
other 0
You can do it as a cross-tab:
select
sum(case when new_used = 'N' then 1 else 0 end) as N,
sum(case when new_used = 'U' then 1 else 0 end) as U,
sum(case when new_used = 'O' then 1 else 0 end) as Other
from myDB
where something = something

Select Distinct Attribute and Print out Count of another even when the count is 0

I don't quite know how I should describe the problem for title, but here's my question.
I have a table named hello with two columns named time and state.
Time | State
Here's an example of the data I have
1 DC
1 VA
1 VA
2 DC
2 MD
3 MD
3 MD
3 VA
3 DC
I would like to get all the possible time and the count of "VA" (0 if "VA" doesn't appear at the time)
The output would look like this
Time Number
1 2
2 0
3 1
I tried to do
SELECT DISTINCT time,
COUNT(state) as Number
FROM hello
WHERE state = 'VA'
GROUP BY time
but it doesn't seem to work.
This is a conditional aggregation:
select time, sum(case when state = 'VA' then 1 else 0 end) as NumVA
from hello
group by time
I want to add that you should never use distinct when you have a group by. The two are redundant. Distinct as a keyword is not even needed in the SQL language; semantically, it is just shorthand for grouping by all the columns.
SELECT TIME,
SUM(CASE WHEN State = 'VA' THEN 1 ELSE 0 END)
FROm tableName
GROUP BY Time
SQLFiddle Demo
One rule of thumb is to get your counts first and put them into a temp for use later.
See below:
Create table temp(Num int, [state] varchar(2))
Insert into temp(Num,[state])
Select 1,'DC'
UNION ALL
Select 1,'VA'
UNION ALL
Select 1,'VA'
UNION ALL
Select 2,'DC'
UNION ALL
Select 2,'MD'
UNION ALL
Select 3,'MD'
UNION All
Select 3,'MD'
UNION ALL
Select 3,'VA'
UNION ALL
Select 3,'DC'
Select t.Num [Time],t.[State]
, CASE WHEN t.[state] = 'VA' THEN Count(t.[State]) ELSE 0 END [Number]
INTO #temp2
From temp t
Group by t.Num, t.[state]
--drop table #temp2
Select
t2.[time]
,SUM(t2.[Number])
From #temp2 t2
group by t2.[time]

How to combine two selects with different where clauses?

select kota ,total, totalsum from
(
SELECT i.[Antam_Unit] as kota ,count(p.[Id_Pks_Pk])as total FROM [SIMPKBL].[dbo].[Pks_Pk] p join [SIMPKBL].[dbo].[Par_Unit_Antam] i on i.Id_Unit_Antam = p.Id_Unit_Antam group by i.[Id_Unit_Antam],i.Antam_Unit
UNION ALL
SELECT i.[Antam_Unit] as kota , count(p.[Id_Proposal_Pk])as totalsum FROM [SIMPKBL].[dbo].[Pks_Pk] p join [SIMPKBL].[dbo].[Par_Unit_Antam] i on i.Id_Unit_Antam = p.Id_Unit_Antam where YEAR(p.Tanggal_Cetak_Pks_Pk) = '2012' group by i.[Id_Unit_Antam],i.Antam_Unit
) t
group by kota,total
I want an output like this:
kota total totalsum
A 12 4
B 16 5
Since the queries are so similar it appears that they can be combined into one select:
select i.[Antam_Unit] as kota,
count(p.[Id_Pks_Pk]) as total,
count( case when YEAR(p.Tanggal_Cetak_Pks_Pk) = '2012' then p.[Id_Proposal_Pk] else null end ) as totalsum
FROM [SIMPKBL].[dbo].[Pks_Pk] p join [SIMPKBL].[dbo].[Par_Unit_Antam] i on i.Id_Unit_Antam = p.Id_Unit_Antam
group by i.[Id_Unit_Antam], i.Antam_Unit
If I understood your requirements correctly, the result you are looking for can be achieved using this simple statement:
SELECT i.[Antam_Unit] as kota,
count(p.[Id_Pks_Pk]) as total,
SUM(CASE WHEN YEAR(p.Tanggal_Cetak_Pks_Pk) = '2012' AND p.[Id_Proposal_Pk] IS NOT NULL THEN 1 ELSE 0 END) as totalsum
FROM [SIMPKBL].[dbo].[Pks_Pk] p
join [SIMPKBL].[dbo].[Par_Unit_Antam] i
on i.Id_Unit_Antam = p.Id_Unit_Antam
group by i.[Id_Unit_Antam],i.Antam_Unit