I need on this query something to group the rows only by CLIENTI.BRAND (customer name/brand). This is a table from a CRM and it contains customers referents names and information and a contact register.
I need something that just displays the rows in this way:
BRAND
BRAND
SITO
NOMINATIVO
EMAIL
TELEFONO
CATEGORIA
DATA_CONTATTO....
BRAND
SITO
NOMINATIVO
EMAIL
TELEFONO
CATEGORIA
DATA_CONTATTO....
BRAND
BRAND
SITO
NOMINATIVO
EMAIL
TELEFONO
CATEGORIA
DATA_CONTATTO....
BRAND
SITO
NOMINATIVO
EMAIL
TELEFONO
CATEGORIA
DATA_CONTATTO....
Here is the query
SELECT
CLIENTI.ID, CLIENTI.BRAND, CLIENTI.SITO,
CONTATTI.NOMINATIVO, CONTATTI.EMAIL, CONTATTI.TELEFONO,
CATEGORIE.CATEGORIA,
REGISTRO.[DATA CONTATTO] AS DATA_CONTATTO,
REGISTRO.AGENZIE, REGISTRO.[NOTE INVIO] AS NOTE_INVIO,
REGISTRO.[INVIATO DA] AS INVIATO_DA, CLIENTI.STATO,
REGISTRO.TIPO_CONTATTO AS [Tipo Contatto],
REGISTRO.[RICONTATTARE], Registro.Data_Ricontattare,
CLIENTI.DataInserimento
FROM
(((CLIENTI
LEFT JOIN
CONTATTI ON CLIENTI.ID = CONTATTI.AZIENDA)
LEFT JOIN
CATEGORIE ON CLIENTI.CATEGORIA = CATEGORIE.ID)
LEFT JOIN
REGISTRO ON CLIENTI.ID = REGISTRO.CLIENTE)
WHERE
BLACKLIST = FALSE
Could you please help me?
Thank you :)
Try following Code:
declare #TableTemp table
(
ID int , BRAND nvarchar(50), SITO nvarchar(50),
NOMINATIVO nvarchar(50), EMAIL nvarchar(50), TELEFONO nvarchar(50)
)
insert into #TableTemp (ID , BRAND , SITO , NOMINATIVO , EMAIL , TELEFONO)
values (1 , N'Brand1', N'Sito1', N'NOMINATIVO1', N'a#f.com' , N'+1454')
insert into #TableTemp (ID , BRAND , SITO , NOMINATIVO , EMAIL , TELEFONO)
values (2 , N'Brand1', N'Sito2', N'NOMINATIVO2', N'ee#f.com' , N'+1754')
insert into #TableTemp (ID , BRAND , SITO , NOMINATIVO , EMAIL , TELEFONO)
values (3 , N'Brand2', N'Sito3', N'NOMINATIVO3', N'a5#f.com' , N'+1434')
insert into #TableTemp (ID , BRAND , SITO , NOMINATIVO , EMAIL , TELEFONO)
values (4 , N'Brand2', N'Sito4', N'NOMINATIVO3', N'e8#f.com' , N'+1954')
insert into #TableTemp (ID , BRAND , SITO , NOMINATIVO , EMAIL , TELEFONO)
values (5 , N'Brand1', N'Sito2', N'NOMINATIVO2', N'ee#f.com' , N'+1754')
insert into #TableTemp (ID , BRAND , SITO,NOMINATIVO , EMAIL , TELEFONO)
select distinct null, BRAND , null, null , null , null from #TableTemp
SELECT BRAND , SITO,NOMINATIVO , EMAIL , TELEFONO FROM #TableTemp
ORDER BY BRAND , ID
After Running SQL Code: (Result)
|BRAND |SITO | NOMINATIVO| EMAIL| TELEFONO|
|:-----|:---:|:----------:|:--------:| --------:|
|Brand1| | | | |
|Brand1|Sito1|NOMINATIVO1 |a#f.com | +1454 |
|Brand1|Sito2|NOMINATIVO2 |ee#f.com | +1754 |
|Brand1|Sito2|NOMINATIVO2 |ee#f.com | +1754 |
|Brand2| | | | |
|Brand2|Sito3|NOMINATIVO3 |a5#f.com | +1434 |
|Brand2|Sito4|NOMINATIVO3 |e8#f.com | +1954 |
Related
I use dynamic properties to manage the characteristics of individuals. I have a table IndividusDynPropValues with 1 line for each individual and each property For example:
ID StartDate ValueString ValueFloat ValueDate Individus_ID IndividusDynProp
14 2018-09-10 Outside NULL NULL 3 Out Status
13 2018-08-15 Dead NULL NULL 1 Out Status
12 2018-08-02 Male NULL NULL 3 Sex
11 2018-07-28 #DBNULL# NULL NULL 1 Out Status
10 2018-07-25 Sold NULL NULL 1 Out Status
9 2018-06-07 Unk NULL NULL 3 Sex
8 2018-06-07 Adult NULL NULL 3 Status
7 2018-06-06 Femal NULL NULL 2 Sex
6 2018-06-06 Adult NULL NULL 2 Status
5 2018-06-03 Male NULL NULL 1 Sex
4 2018-06-03 Adult NULL NULL 1 Status
3 2018-05-23 Egg NULL NULL 3 Status
2 2018-05-23 Egg NULL NULL 2 Status
1 2018-05-21 Egg NULL NULL 1 Status
'#DBNULL#' means that the individual is on site again. I want to create a function that takes a date for the input parameter and returns a table with the ID of each individual who belong to the groups “Male living on site” at the date. An individual is part of the group if Sex = 'Male' AND (Out Status IS NULL OR Out Status = '#DBNULL#')
So in the example, if the date enter in the function is “2018-07-20” it returns:
Individus_ID
1
if the date is “2018-08-10” it returns:
Individus_ID
3
1
if the date is “2018-08-17” it returns:
Individus_ID
3
I’ve tried that:
CREATE FUNCTION fn_Groupe_Individus_Male_Vivant (#daDate datetime)
RETURNS #TGrMalesVivants TABLE (
TList_Individual [varchar] (50) NOT NULL
)
AS
BEGIN
DECLARE #TtempGrMalesVivants TABLE (TList_Individual [varchar] (50) NOT NULL)
DECLARE #TtempGrMales TABLE (TList_MIndividual int NOT NULL)
INSERT INTO #TtempGrMales
SELECT DISTINCT Individus_ID
FROM IndividusDynPropValues
DECLARE #selectedOutStatus VARCHAR(50),
#sBirdId int,
#tmpSex VARCHAR(3)
WHILE EXISTS (SELECT * FROM #TtempGrMales)
BEGIN
SELECT TOP 1 #sBirdId = TList_MIndividual FROM #TtempGrMales
SELECT #selectedOutStatus =IDPV.ValueString
FROM [dbo].[IndividusDynPropValues] AS IDPV
WHERE NOT EXISTS (SELECT *
FROM [dbo].[IndividusDynPropValues] AS IDPV2
WHERE IDPV.Individus_ID=IDPV2.Individus_ID
AND IDPV.IndividusDynProp_ID=IDPV2.IndividusDynProp_ID
AND IDPV2.StartDate>IDPV.StartDate AND CONVERT(smalldatetime,IDPV2.StartDate,120 )<=#daDate)
AND CONVERT(smalldatetime,IDPV.StartDate,120 )<=#daDate
AND IDPV.Individus_ID =#sBirdId
AND IDPV.IndividusDynProp_ID='Out Status'
SELECT #tmpSex= IDPV.ValueString
FROM [dbo].[IndividusDynPropValues] AS IDPV
INNER JOIN TSaisie AS TS ON TS.TSai_PK_ID=IDPV.Saisie_ID
INNER JOIN TProtocole AS TP ON TP.TPro_PK_ID=TS.TSai_FK_TPro_ID
WHERE NOT EXISTS (SELECT *
FROM [dbo].[IndividusDynPropValues] AS IDPV2
WHERE IDPV.Individus_ID=IDPV2.Individus_ID
AND IDPV.IndividusDynProp_ID=IDPV2.IndividusDynProp_ID
AND IDPV2.StartDate>IDPV.StartDate AND CONVERT(smalldatetime,IDPV2.StartDate,120 )<=#daDate)
AND CONVERT(smalldatetime,IDPV.StartDate,120 )<=#daDate
AND IDPV.Individus_ID =#sBirdId
AND IDPV.IndividusDynProp_ID='Sex'
AND TPro_Importance = (SELECT Max(TP2.Tpro_Importance)
FROM IndividusDynPropValues IDPV3
INNER JOIN TSaisie AS TS2 ON TS2.TSai_PK_ID=IDPV3.Saisie_ID
INNER JOIN TProtocole AS TP2 ON TP2.TPro_PK_ID=TS2.TSai_FK_TPro_ID
WHERE IDPV3.Individus_ID=#sBirdId
AND IDPV3.IndividusDynProp_ID=4
AND IDPV3.StartDate>=IDPV.StartDate
AND CONVERT(smalldatetime,IDPV3.StartDate,120 )<=#daDate)
IF #tmpSex='Male' AND (#selectedOutStatus IS NULL OR #selectedOutStatus='#DBNULL#')
BEGIN
INSERT INTO #TtempGrMalesVivants (TList_Individual)
VALUES (#sBirdId)
END
DELETE TOP (1) FROM #TtempGrMales
END
INSERT #TGrMalesVivants
SELECT *
FROM #TtempGrMalesVivants
RETURN
END
it works but it takes 1:55 with all the table (1859732 lines) so it’s too long
I think I understand what you are trying to do. Notice how I posted sample data? This is a good example for what you should do in the future.
Some conditional aggregation should work here. You need this aggregation because your data is denormalized into an EAV and you need to reassemble this into a normalized table. This works for the sample data and your desired output. You can uncomment the set #MyDate line to see the second value working.
if OBJECT_ID('tempdb..#IndividusDynPropValues') is not null
drop table #IndividusDynPropValues
create table #IndividusDynPropValues
(
ID int
, StartDate date
, ValueString varchar(50)
, ValueFloat float
, ValueDate date
, Individus_ID int
, IndividusDynProp varchar(50)
)
insert #IndividusDynPropValues values
(14, '2018-09-10', 'Outside', NULL, NULL, 3, 'Out Status')
, (13, '2018-08-15', 'Dead', NULL, NULL, 1, 'Out Status')
, (12, '2018-08-02', 'Male', NULL, NULL, 3, 'Sex')
, (11, '2018-07-28', '#DBNULL#', NULL, NULL, 1, 'Out Status')
, (10, '2018-07-25', 'Sold', NULL, NULL, 1, 'Out Status')
, (9 , '2018-06-07', 'Unk' , NULL, NULL, 3, 'Sex')
, (8 , '2018-06-07', 'Adult' , NULL, NULL, 3, 'Status')
, (7 , '2018-06-06', 'Femal' , NULL, NULL, 2, 'Sex')
, (6 , '2018-06-06', 'Adult' , NULL, NULL, 2, 'Status')
, (5 , '2018-06-03', 'Male' , NULL, NULL, 1, 'Sex')
, (4 , '2018-06-03', 'Adult' , NULL, NULL, 1, 'Status')
, (3 , '2018-05-23', 'Egg' , NULL, NULL, 3, 'Status')
, (2 , '2018-05-23', 'Egg' , NULL, NULL, 2, 'Status')
, (1 , '2018-05-21', 'Egg' , NULL, NULL, 1, 'Status')
declare #MyDate date = '20180720' --returns Individus_ID 1
--set #MyDate = '20180810' --returns Individus_ID 1, 3
;
with MySortedData as
(
select i.*
, RowNum = ROW_NUMBER()over(partition by i.Individus_ID, i.IndividusDynProp order by i.StartDate desc)
from #IndividusDynPropValues i
where i.StartDate <= #MyDate
)
select s.Individus_ID
, OutStatus = max(case when IndividusDynProp = 'Out Status' then ValueString end)
, Status = max(case when IndividusDynProp = 'Status' then ValueString end)
, Sex = max(case when IndividusDynProp = 'Sex' then ValueString end)
from MySortedData s
where s.RowNum = 1
group by s.Individus_ID
having isnull(max(case when IndividusDynProp = 'Out Status' then ValueString end), '#DBNULL#') = '#DBNULL#'
and max(case when IndividusDynProp = 'Sex' then ValueString end) = 'Male'
MS SQL Server
i want the sum of salaries of all the employees along with manager salary under a single manager
CREATE TABLE #empsal
(
Empid int,
empname varchar(50),
managerid int,
salary int
)
INSERT INTO #empsal
VALUES
(1 , 'manager' , NULL , 500),
(2 , 'manager1' , NULL , 600),
(3 , 'd' , 1 , 100),
(4 , 'f' , 3 , 200),
(5 , 'g' , 4 , 300),
(6 , 'h' , 2 , 800),
(8 , 'j' , 6 , 200),
(7 , 'I' , 6 , 140),
(8 , 'j' , 6 , 200)
i want the result as below
empid sumof salary
1 1100(500+100+200+300)
2 1940 (600+800+200+140+200)
here employee 3 is having manager as 1 and employee 4 is having manager as 3 and employee 5 is having manager as 4 so over all the employees are under manager 1 . so i want the sum of all salaries under a manager. Please help me to sort out
Use a recursive CTE to link the managers to each employee, then group by the highest one.
;WITH Relationships AS
(
SELECT
TopManagerID = E.Empid,
RelatedEmployeeID = E.Empid
FROM
#empsal AS E
WHERE
E.managerid IS NULL
UNION ALL
SELECT
TopManagerID = E.TopManagerID,
RelatedEmployeeID = X.Empid
FROM
Relationships AS E
INNER JOIN #empsal AS X ON E.RelatedEmployeeID = X.managerid
)
SELECT
R.TopManagerID,
SumSalary = SUM(E.salary)
FROM
Relationships AS R
INNER JOIN #empsal AS E ON R.RelatedEmployeeID = E.Empid
GROUP BY
R.TopManagerID
Please note that you have 2 employees with ID 8 (should be unique) on your sample data (it will give incorrect results until you update it).
Let's say I have this table (this is simplified, of course there are other columns):
CompanyID (int)
ContactName (varchar(50))
ContactType (char(1))
with the values:
CompanyID | ContactName | ContactType
-----------------------------------------------
1 | John Doe | A
1 | Jane Smith | B
2 | Ralph Jones | B
3 | Dick Grayson | A
What I want are all the companies where there's a ContactType='A', unless there is no ContactType='A' return the ContactType='B'. So in this example, I want:
1, John Doe (because he's a ContactType A)
2, Ralph Jones (because Company #2 doesn't have a ContactType A)
3, Dick Grayson (because he's a ContactType A)
I can't just say "A or B" because a company may have both.
Here's what I tried (and failed)
use MyFancyDatabase
drop table #TypeA
drop table #TypeB
drop table #TypeAB
create table #TypeA(ownerkey int, ContactName varchar(200), ContactType char(1))
insert #TypeA
Select ownerkey, ContactName, ContactType from address
where ContactType = 'A' and CancelDate is null
create table #TypeB(ownerkey int, ContactName varchar(200), ContactType char(1))
insert #TypeB
Select ownerkey, ContactName, ContactType from address
where ContactType = 'B' and CancelDate is null
create table #TypeAB(ownerkey int, ContactName varchar(200), ContactType char(1))
insert #TypeAB
select * from #TypeA
except
select * from #TypeB
I guess in English it's "A, but if there is no A, then take B."
Any suggestions?
SELECT a.OwnerKey, a.CompanyName, Case WHEN a.ContactType IS NULL THEN b.ContactType ELSE a.ContactType END AS ContactType
FROM #TypeA a
LEFT JOIN #TypeB b on a.OwnerKey = b.OwnerKey
I think this should work for you.
with SortedResults as
(
select CompanyID
, ContactName
, ContactType
, ROW_NUMBER() over (partition by CompanyID order by ContactType) as RowNum
from ThisTable
)
select *
from SortedResults
where RowNum = 1
Try this SQL
Select t1.CompanyID ,
ContactName = IIF(t1.ContactType='A',t1.ContactName,t2.ContactName)
ContactType = IIF(t1.ContactType='A','A',t2.ContactType)
FROM address as t1 left join address as t2
on t1.CompanyID = t2.CompanyID
AND t1.ContactName = t2.ContactName
AND (t1.ContactType <> t2.ContactType)
IF you have more type than A OR B and you want just A and B add this on the where statment
WHERE (t1.ContactType = 'A' OR t1.ContactType = 'B')
AND (t2.ContactType = 'A' OR t2.ContactType = 'B')
The columns in your defined table don't appear to match with the ones in your example query. I'm guessing OwnerKey is the same as CompanyID?
If so, and you keep most of the rest of your code, the last select would need to be:
select * from #TypeA
union all
select * from #TypeB
where not exists (
select *
from #TypeA
where #TypeA.ownerkey = #TypeB.ownerkey)
In a table called USERACCOUNT, records are as given below,
User Name | Gmail | Yahoo | Hotmail
Sankar | X | NULL | NULL
Aravinth | NULL | X | NULL
Pavithran | NULL | NULL | X
My excepted result is:
User Name | Gmail | Yahoo | Hotmail
Sankar | X | X | X
Please help me regarding this,
Thanks in advance
you have to check each column is it NULL or not with the help of ISNULL
declare #temp table
(
name nvarchar(11),
gmail nvarchar(11),
yahoo nvarchar(11),
hotmail nvarchar(11))
insert into #temp values ('snkar' ,'X' , NULL, NULL)
insert into #temp values ('avinth' ,NULL, 'Y' , NULL)
insert into #temp values ('vithran',NULL,NULL ,'Z' )
select * from #temp
select
name,isnull(gmail,isnull(yahoo,hotmail)) gmail,
isnull(yahoo,isnull(gmail,hotmail)) yahoo,
isnull(hotmail,isnull(gmail,yahoo)) hotmail
from #temp
and if we have multiple rows with same name like that and we have to filter data same as then this method will helpful
insert into #temp values ('snkar' ,'X' , NULL, NULL)
insert into #temp values ('snkar' ,NULL, 'X' , NULL)
insert into #temp values ('snkar',NULL,NULL ,'X' )
select name,max(gmail) gmail,max(yahoo) yahoo,max(hotmail) hotmail
from #temp
group by name
COALESCE is more suitable
DECLARE #temp TABLE
(
name nvarchar(11),
gmail nvarchar(11),
yahoo nvarchar(11),
hotmail nvarchar(11)
)
INSERT INTO #temp VALUES ('snkar' ,'X' , NULL, NULL)
INSERT INTO #temp VALUES ('avinth' ,NULL, 'Y' , NULL)
INSERT INTO #temp VALUES ('vithran',NULL,NULL ,'Z' )
SELECT *
FROM #temp
SELECT
name, COALESCE(gmail,yahoo,hotmail) gmail,
COALESCE(yahoo,gmail,hotmail) yahoo,
COALESCE(hotmail,gmail,yahoo) hotmail
FROM #temp
Data Set 1:
Cust_Ref | ACC1 | ACC2 | ACC3
------------+-----------+-----------+---------
1000001 | ALPHA | BRAVO | CHARLIE
1000002 | ALPHA | BRAVO | CHARLIE
1000003 | ALPHA | BRAVO | CHARLIE
1000004 | DELTA | ECHO |
1000005 | DELTA | ECHO |
1000006 | FOXTROT |
1000007 | FOXTROT |
Data Set 2:
Cust_Ref | ACC
------------+--------
1000001 | ALPHA
1000001 | BRAVO
1000001 | DELTA
1000004 | DELTA
1000004 | ECHO
1000006 | FOXTROT
Data Set 1 shows the customer references and the accounts they should have. So for example 1000001 must have the accounts - ALPHA, BRAVO, CHARLIE. Customer 1000002 has DELTA and ECHO, etc.
Data Set 2 shows what accounts are actually associated with a customer reference.
Is there where I can return instances of missing accounts with T-SQL?
Example:
In the dataset I have provided customer 1000001 should have ALPHA, BRAVO, CHARLIE but Data Set 2 shows that the customer does not have CHARLIE.
Considering this DDL and sample data:
DECLARE #Table1 TABLE (
Cust_Ref VARCHAR(10) PRIMARY KEY,
ACC1 VARCHAR(10) NULL,
ACC2 VARCHAR(10) NULL,
ACC3 VARCHAR(10) NULL
)
INSERT INTO #Table1 VALUES
('1000001','ALPHA','BRAVO','CHARLIE'),
('1000002','ALPHA','BRAVO','CHARLIE'),
('1000003','ALPHA','BRAVO','CHARLIE'),
('1000004','DELTA','ECHO',NULL),
('1000005','DELTA','ECHO',NULL),
('1000006','FOXTROT','FOXTROT',NULL),
('1000007','FOXTROT','FOXTROT',NULL)
DECLARE #Table2 TABLE (
Cust_Ref VARCHAR(10) NOT NULL,
ACC VARCHAR(10) NOT NULL
)
INSERT INTO #Table2 VALUES
('1000001','ALPHA'),
('1000001','BRAVO'),
('1000001','DELTA'),
('1000004','DELTA'),
('1000004','ECHO'),
('1000006','FOXTROT')
You could use UNPIVOT and EXCEPT, this way:
SELECT Cust_Ref, ACC
FROM #Table1 UNPIVOT (ACC FOR COL IN (ACC1, ACC2, ACC3)) U
EXCEPT
SELECT Cust_Ref, ACC
FROM #Table2
(Select cust_ref, acc1 account
from dataSet1
union
Select cust_ref, acc2 account
from dataSet1
union
Select cust_ref, acc3 account
from dataSet1)z
Where Not exists (Select * from dataSet2
where cust_ref = z.CustRef
and acc = z.account)
WITH DataSet1 AS ( -- Define DataSet1
SELECT *
FROM (VALUES
(1000001, 'ALPHA', 'BRAVO', 'CHARLIE')
, (1000002, 'ALPHA', 'BRAVO', 'CHARLIE')
, (1000003, 'ALPHA', 'BRAVO', 'CHARLIE')
, (1000004, 'DELTA', 'ECHO', NULL)
, (1000005, 'DELTA', 'ECHO', NULL)
, (1000006, 'FOXTROT', NULL, NULL)
, (1000007, 'FOXTROT', NULL, NULL)
) A (Cust_Ref, ACC1, ACC2, ACC3)
), DataSet2 AS ( -- Define DataSet2
SELECT *
FROM (VALUES
(1000001, 'ALPHA')
, (1000001, 'BRAVO')
, (1000004, 'DELTA')
, (1000004, 'ECHO')
, (1000006, 'FOXTROT')
) A (Cust_Ref, ACC)
)
SELECT A.Cust_Ref
, B.ACC
FROM DataSet1 A
CROSS APPLY(VALUES -- Pivot ACC1, ACC2, and ACC3 into ACC
(A.ACC1)
, (A.ACC2)
, (A.ACC3)
) B (ACC)
WHERE B.ACC IS NOT NULL -- Remove NULL ACCs
AND NOT EXISTS ( -- Remove ACCs that exist in DataSet2
SELECT 1
FROM DataSet2
WHERE A.Cust_Ref = Cust_Ref
AND B.ACC = ACC
);