How to get value from another row in SQL?
ID DeletedPersonID ProductKey PartyID RespID
9 461 17 33 95
10 95 17 34 95
and I have this select statement
select
drp.ID,
drp.DeletedPersonID,
drp.ProductID,
case when drp.DeletedPersonID != drp.RespID then (Get Party Key by RespID) else drp.PartyID end as 'PartyID',
case when drp.DeletedPersonID != drp.RespID then (Get Party Key by RespID) else drp.PartyName end as 'PartyName',
case when drp.DeletedPersonID = drp.RespID then null else drp.PartyID end as 'SubPartyID',
from dbo.RespHistory drp
In above example since ID = 10 has the same DeletedPersonID and RespID value I like to use the same PartyID but in ID = 9 or in the first line Since DeletedPersonID and RespID are difference I want to use PartyID of ID = 10
I am looking a view similar to shown below
ID DeletedPersonID ProductKey PartyID PartyName SubPartyID
9 461 17 34 ABC 33
10 95 17 34 XYZ null
Something like this
with equals_cte (RespID) as (
select RespID
from dbo.RespHistory
where DeletedPersonID = RespID
)
select
drp.ID, drp.DeletedPersonID, drp.ProductKey, coalesce(ec.RespID, drp.RespID) PartyID
, drp.PartyName, drp.RespID
, iif(drp.DeletedPersonID = drp.RespID, null, drp.RespID) SubPartyID
from dbo.RespHistory drp
left join equals_cte ec on drp.RespID = ec.RespID;
I currently have a data in a table positioned vertically:
FILE ID: 001
RECORD 1 1111
RECORD 2 123456789012345
RECORD 3 A01 11
RECORD 4 A02 11
RECORD 5 A03 11
RECORD 6 0103050
RECORD 7 777
RECORD 8 A01 1
RECORD 9 A02 1
RECORD 10 A03 1111
RECORD 11 A04 11111
FILE ID: 002
RECORD 1 2222
RECORD 2 1234567
RECORD 3 A01 11
RECORD 4 A02 11
RECORD 5 A03 11
RECORD 6 0103050
RECORD 7 777
RECORD 8 A01 1
RECORD 9 A02 1
RECORD 10 A03 1111
RECORD 11 A04 11111
FILE ID: 003
RECORD 1 3333
RECORD 2 1234567
RECORD 3 A01 11
RECORD 4 A02 11
RECORD 5 A03 11
RECORD 6 0103050
RECORD 7 777
RECORD 8 A01 1
RECORD 9 A02 1
RECORD 10 A03 1111
RECORD 11 A04 11111
How can I insert it into another table so it is positioned horizontally, the following way:
FileID|Record1|Record2|Record3|Record4|Record5|Record6|Record7|Record8|Record9|Record10|Record11
--------------------------------------------------------------------------------------------------
001 |1111 |1111111|A01 11|A02 11|A03 11|0103050|777 |A01 1|A02 1|A03 1111|A04 11111
002 |2222 |1234567|A01 11|A02 11|A03 11|0103050|777 |A01 1|A02 1|A03 1111|A04 11111
003 |3333 |1234567|A01 11|A02 11|A03 11|0103050|777 |A01 1|A02 1|A03 1111|A04 11111
Thank's
I'm a little late to the party, but I'll give it a shot. This will only work if your data is consistent with file id followed by 11 records. First, you need to have a table with an identity column. I would make it a habit to do so when creating tables. Do your bulk insert into the following table. This will store your data with row id's which will be important later.
CREATE TABLE [dbo].[Table_1](
[TableId] [bigint] IDENTITY(1,1) NOT NULL,
[Column1] [varchar](255) NULL,
[Column2] [varchar](255) NULL
) ON [PRIMARY]
GO
Create this table for the pivoted data.
CREATE TABLE [dbo].[Table_2](
[Table2ID] [bigint] IDENTITY(1,1) NOT NULL,
[FileID] [varchar](255) NULL,
[Record1] [varchar](255) NULL,
[Record2] [varchar](255) NULL,
[Record3] [varchar](255) NULL,
[Record4] [varchar](255) NULL,
[Record5] [varchar](255) NULL,
[Record6] [varchar](255) NULL,
[Record7] [varchar](255) NULL,
[Record8] [varchar](255) NULL,
[Record9] [varchar](255) NULL,
[Record10] [varchar](255) NULL,
[Record11] [varchar](255) NULL
) ON [PRIMARY]
GO
Now to get the data from table 1 to table 2. I will use a Common Table Expression (CTE) and the LEAD function.
WITH preselect AS
(
SELECT Column1
,Column2 AS 'FileID'
,LEAD(Column2,1,0) OVER(ORDER BY TableId) AS 'Record1'
,LEAD(Column2,2,0) OVER(ORDER BY TableId) AS 'Record2'
,LEAD(Column2,3,0) OVER(ORDER BY TableId) AS 'Record3'
,LEAD(Column2,4,0) OVER(ORDER BY TableId) AS 'Record4'
,LEAD(Column2,5,0) OVER(ORDER BY TableId) AS 'Record5'
,LEAD(Column2,6,0) OVER(ORDER BY TableId) AS 'Record6'
,LEAD(Column2,7,0) OVER(ORDER BY TableId) AS 'Record7'
,LEAD(Column2,8,0) OVER(ORDER BY TableId) AS 'Record8'
,LEAD(Column2,9,0) OVER(ORDER BY TableId) AS 'Record9'
,LEAD(Column2,10,0) OVER(ORDER BY TableId) AS 'Record10'
,LEAD(Column2,11,0) OVER(ORDER BY TableId) AS 'Record11'
FROM Table_1
)
INSERT INTO Table_2
SELECT FileID,Record1,Record2,Record3,Record4,Record5,Record6,Record7
,Record8,Record9,Record10,Record11
FROM preselect
WHERE Column1 = 'FILE ID:'
I am ordering by the TableId in the LEAD function to ensure the order of the data. Then it is just a matter of getting the FileId value along with the values of the next 11 rows.
LEAD (Transact-SQL
Common Table Expression (CTE)
I am running a query that selects data from a SQL Server view. When the data comes back it is rounded to not have any decimal places. This does not happen to every column even though all the columns are defined the same in the SQL base table:
[whp] [numeric](10, 2) NULL,
[whp_si] [numeric](10, 2) NULL,
In this instance the Access query column whp_si shows the decimal places always but whp does not, ever.
Looking at the data whp_si in SQL, the majority of records have decimal places, whereas the majority do not for whp, I cannot believe that this would make any difference but you never know.
When I look at the linked SQL base table via Access in design mode, it interprets both columns as Number, Decimal, Precision 10, Scale 2, Decimal Places Auto. When I look at the SQL view it shows whp as Long Integer and whp_si as Double.
The view is almost a like for like representation of the the base table, there is no formatting whatsoever. The users can not see the base tables they have to use the views.
Can anybody help me with this, please, as I have searched the entire world wide web, I think.
Base table def:
CREATE TABLE [dbo].[test](
[id] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[id_wellborecompl] [int] NULL,
[id_validation_level] [int] NULL,
[id_type_test] [int] NULL,
[id_status_test] [int] NULL,
[date] [datetime2](6) NOT NULL,
[duration] [numeric](10, 2) NULL,
[q_oil] [numeric](10, 2) NULL,
[q_gas] [numeric](10, 2) NULL,
[q_water] [numeric](14, 2) NULL,
[api] [numeric](10, 2) NULL,
[bsw] [numeric](10, 2) NULL,
[gor] [numeric](14, 2) NULL,
[glr] [numeric](14, 2) NULL,
[tds] [numeric](10, 2) NULL,
[choke] [numeric](10, 2) NULL,
[whp] [numeric](10, 2) NULL,
[whp_si] [numeric](10, 2) NULL,
[flp] [numeric](10, 2) NULL,
[flp_SI] [numeric](10, 2) NULL,
[wht] [numeric](10, 2) NULL,
[wht_SI] [numeric](10, 2) NULL,
[chp] [numeric](10, 2) NULL,
[chp_SI] [numeric](10, 2) NULL,
[p_sep] [numeric](10, 2) NULL,
[p_sep_si] [numeric](10, 2) NULL,
[t_sep] [numeric](10, 2) NULL,
[t_sep_si] [numeric](10, 2) NULL,
[chemical_inj] [numeric](10, 2) NULL,
[bhp_pip] [numeric](10, 2) NULL,
[bhp_pip_si] [numeric](10, 2) NULL,
[q_gl] [numeric](14, 2) NULL,
[q_jet] [numeric](10, 2) NULL,
[rpm] [numeric](10, 2) NULL,
[frequency] [numeric](10, 2) NULL,
[stroke] [numeric](10, 2) NULL,
[submergence] [numeric](10, 2) NULL,
[submergence_si] [numeric](10, 2) NULL,
[amp] [numeric](10, 2) NULL,
[pd] [numeric](10, 2) NULL,
[pd_si] [numeric](10, 2) NULL,
[volts] [numeric](10, 2) NULL,
[chole_gl] [numeric](10, 2) NULL,
[p_jet] [numeric](10, 2) NULL,
[p_jet_si] [numeric](10, 2) NULL,
[p_gl] [numeric](10, 2) NULL,
[p_gl_si] [numeric](10, 2) NULL,
[pump_eff] [numeric](10, 2) NULL,
[validity] [bit] NULL,
[comments] [nvarchar](255) NULL,
[last_update] [datetime2](6) NULL,
[user_update] [nvarchar](255) NULL,
[comment] [varchar](max) NULL,
[deletedAt] [datetime2](6) NULL,
[create_date] [datetime2](6) NULL,
[t_motor] [numeric](10, 2) NULL,
[t_motor_si] [numeric](10, 2) NULL,
[bh_temp] [numeric](10, 2) NULL,
[bh_temp_si] [numeric](10, 2) NULL,
[vibration] [numeric](10, 2) NULL,
[sand] [numeric](10, 2) NULL,
PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Snippet of data returned from table with Select statement:
whp whp_si flp flp_SI
6.6 0.46 NULL NULL
120.6 8.32 88.9 6.13
128.5 8.87 NULL NULL
2 0.14 1.8 0.12
2.8 0.19 NULL NULL
7.1 0.49 NULL NULL
120.6 8.32 98.8 6.82
128.5 8.87 NULL NULL
3 0.21 NULL NULL
9 0.62 NULL NULL
9 0.62 NULL NULL
9 0.62 NULL NULL
7.1 0.49 NULL NULL
2 0.14 1.8 0.12
2.8 0.19 2.3 0.16
123.3 8.51 82.9 5.72
128.5 8.87 0 0
4 0.28 NULL NULL
9 0.62 NULL NULL
7.1 0.49 NULL NULL
View Def:
ALTER VIEW [dbo].[V_RAW_Test] AS
SELECT T.[id] AS id
,T.[id_wellborecompl] AS id_wellborecompl
,T.[id_validation_level] AS id_validation_level
,T.[id_type_test] AS id_type_test
,T.[id_status_test] AS id_status_test
,T.[date] AS date
,T.[duration] AS duration
,T.[q_oil] AS q_oil
,T.[q_gas] AS q_gas
,T.[q_water] AS q_water
,T.[api] AS api
,T.[bsw] AS bsw
,T.[gor] AS gor
,T.[glr] AS glr
,T.[tds] AS tds
,T.[choke] AS choke
,T.[whp] AS whp
,T.[whp_si] AS whp_si
,T.[flp] AS flp
,T.[flp_SI] AS flp_SI
,T.[wht] AS wht
,T.[wht_SI] AS wht_SI
,T.[chp] AS chp
,T.[chp_SI] AS chp_SI
,T.[p_sep] AS p_sep
,T.[p_sep_si] AS p_sep_si
,T.[t_sep] AS t_sep
,T.[t_sep_si] AS t_sep_si
,T.[chemical_inj] AS chemical_inj
,T.[bhp_pip] AS bhp_pip
,T.[bhp_pip_si] AS bhp_pip_si
,T.[q_gl] AS q_gl
,T.[q_jet] AS q_jet
,T.[rpm] AS rpm
,T.[frequency] AS frequency
,T.[stroke] AS stroke
,T.[submergence] AS submergence
,T.[submergence_si] AS submergence_si
,T.[amp] AS amp
,T.[pd] AS pd
,T.[pd_si] AS pd_si
,T.[volts] AS volts
,T.[chole_gl] AS chole_gl
,T.[p_jet] AS p_jet
,T.[p_jet_si] AS p_jet_si
,T.[p_gl] AS p_gl
,T.[p_gl_si] AS p_gl_si
,T.[pump_eff] AS pump_eff
,T.[validity] AS validity
,T.[comments] AS comments
,T.[last_update] AS last_update
,T.[user_update] AS user_update
,T.[comment] AS comment
,T.[deletedAt] AS deletedAt
,(SELECT TOP 1 A.id FROM [dbo].[activation] AS A WITH (NOLOCK) WHERE A.id_wellstring = WS.id AND T.date >= A.date_run AND (T.date < A.date_end OR A.date_end IS NULL) AND A.deletedAt IS NULL) AS id_activation
FROM [dbo].[test] AS T WITH (NOLOCK)
INNER JOIN [dbo].[wellbore_compl] WC ON WC.id = T.id_wellborecompl
INNER JOIN [dbo].[wellstring] WS ON WS.id = WC.id_wellstring
Snippet of data from View Select statement:
whp whp_si flp flp_SI wht wht_SI
6.6 0.46 NULL NULL NULL NULL
120.6 8.32 88.9 6.13 71.4 4.93
128.5 8.87 NULL NULL NULL NULL
2 0.14 1.8 0.12 NULL NULL
2.8 0.19 NULL NULL NULL NULL
7.1 0.49 NULL NULL NULL NULL
120.6 8.32 98.8 6.82 70.9 4.89
128.5 8.87 NULL NULL NULL NULL
3 0.21 NULL NULL NULL NULL
9 0.62 NULL NULL NULL NULL
9 0.62 NULL NULL NULL NULL
9 0.62 NULL NULL NULL NULL
7.1 0.49 NULL NULL NULL NULL
2 0.14 1.8 0.12 NULL NULL
2.8 0.19 2.3 0.16 39 2.69
123.3 8.51 82.9 5.72 65.5 4.52
128.5 8.87 0 0 NULL NULL
4 0.28 NULL NULL NULL NULL
9 0.62 NULL NULL NULL NULL
7.1 0.49 NULL NULL NULL NULL
Access query:
SELECT dbo_V_RAW_Test.id, dbo_V_RAW_Test.q_gas, dbo_V_RAW_Test.q_water, dbo_V_RAW_Test.whp, dbo_V_RAW_Test.whp_si, dbo_test.whp, dbo_test.whp_si, dbo_V_RAW_Test.flp, dbo_V_RAW_Test.flp_SI, dbo_V_RAW_Test.wht, dbo_V_RAW_Test.wht_SI, dbo_V_RAW_Test.chp, dbo_V_RAW_Test.chp_SI, dbo_V_RAW_Test.p_sep, dbo_V_RAW_Test.p_sep_si, dbo_V_RAW_Test.t_sep, dbo_V_RAW_Test.t_sep_si, dbo_V_RAW_Test.chemical_inj, dbo_V_RAW_Test.bhp_pip, dbo_V_RAW_Test.bhp_pip_si, dbo_V_RAW_Test.q_gl, dbo_V_RAW_Test.q_jet, dbo_V_RAW_Test.rpm, dbo_V_RAW_Test.frequency, dbo_V_RAW_Test.stroke, dbo_V_RAW_Test.submergence, dbo_V_RAW_Test.submergence_si, dbo_V_RAW_Test.amp, dbo_V_RAW_Test.pd, dbo_V_RAW_Test.pd_si, dbo_V_RAW_Test.volts, dbo_V_RAW_Test.chole_gl, dbo_V_RAW_Test.p_jet, dbo_V_RAW_Test.p_jet_si, dbo_V_RAW_Test.p_gl, dbo_V_RAW_Test.p_gl_si, dbo_V_RAW_Test.pump_eff, dbo_V_RAW_Test.validity, dbo_V_RAW_Test.comments, dbo_V_RAW_Test.last_update, dbo_V_RAW_Test.user_update, dbo_V_RAW_Test.comment, dbo_V_RAW_Test.deletedAt, dbo_V_RAW_Test.id_activation
FROM dbo_V_RAW_Test
WHERE (((dbo_V_RAW_Test.validity)=False) AND ((dbo_V_RAW_Test.deletedAt) Is Null));
Snippet from Access query, just a straight Select:
id date q_oil q_gas q_water api bsw gor glr tds choke whp whp_si flp flp_SI wht wht_SI
52001 2017-02-03 60 133 781 92.87 2216 158 192 6 0.46
52002 2017-02-03 306 20000 27.7 75 8.11 65359 60060 87 120 8.32 88 6.13 71 4.93
52003 2017-02-03 0 0 0 128 8.87
52004 2017-02-04 595 274 465 43.87 460 258 2 0.14 1 0.12
52005 2017-02-04 372 66 2754 88.1 177 21 2 0.19
52006 2017-02-04 26 127 4 13.33 4884 4233 55 7 0.49
52007 2017-02-04 272 19724 11.16 75 3.89 72514 69696 85 120 8.32 98 6.82 70 4.89
52008 2017-02-04 0 0 0 128 8.87
52009 2017-02-04 71 194 1405 95 2732 131 3 0.21
52010 2017-02-04 458 290 40 8 634 583 9 0.62
52011 2017-02-04 39 20 31 44 511 286 9 0.62
52012 2017-02-04 67 639 24 26 9543 7030 9 0.62
52013 2017-02-05 29 141 1 3.33 4862 4700 55 7 0.49
52014 2017-02-05 585 280 470 44.55 478 265 192 2 0.14 1 0.12
52015 2017-02-05 380 66 2743 87.83 173 21 192 2 0.19 2 0.16 39 2.69
52016 2017-02-05 247 16714 14.26 75 5.36 67668 64038 88 123 8.51 82 5.72 65 4.52
52017 2017-02-05 0 0 0 0 128 8.87 0 0
52018 2017-02-05 151 43 394 72 286 79 4 0.28
52019 2017-02-05 367 247 61 14 673 577 9 0.62
52020 2017-02-06 32 128 2 5.88 4000 3764 55 7 0.49
I've two tables: -
sales
CREATE TABLE `sales` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
`description` text,
`quantity` int(10) DEFAULT NULL,
`price` decimal(18,2) DEFAULT NULL,
`payment_method_id` int(10) DEFAULT NULL,
`user_id` int(10) DEFAULT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
sale_details
CREATE TABLE `sale_details` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`sale_id` int(10) DEFAULT NULL,
`product_id` int(10) DEFAULT NULL,
`quantity` int(10) DEFAULT NULL,
`price` decimal(18,2) DEFAULT NULL,
`total_price` decimal(18,2) DEFAULT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
I need to insert data into these tables accordingly using ajax. First of all, I structured my array data into the following.
Here is my data,
[
'quantity' => 3,
'price' => 63,
'payment_method_id' => 1,
'user_id' => 1,
'sale_details' => [
0 => [
'product_id' => 1,
'quantity' => 2,
'price' => 24,
'total_price' => 48
],
1 => [
'product_id' => 49,
'quantity' => 1,
'price' => 15,
'total_price' => 15
]
]
]
SalesController.php
if ($this->request->is('ajax')) {
$sales = $this->Sales->newEntity(
$this->request->data(),
[
'validate' => 'create',
'associated' => [
'SaleDetails' => ['validate' => 'create']
]
]
);
if ($this->Sales->save($sales)) {
//code
}
}
I manage to insert data into those tables but primary key of both tables keep increasing with addition number of 2. I inserted the data for 3 times. Here is how the data recorded: -
sales
id title description quantity price payment_method_id user_id created modified
------ ------ ----------- -------- ------ ----------------- ------- ------------------- ---------------------
1 (NULL) (NULL) 3 63.00 1 1 2017-03-03 11:37:11 2017-03-03 11:37:11
sale_details
id sale_id product_id quantity price total_price created modified
------ ------- ---------- -------- ------ ----------- ------------------- ---------------------
1 1 1 2 24.00 48.00 2017-03-03 11:37:11 2017-03-03 11:37:11
2 1 49 1 15.00 15.00 2017-03-03 11:37:11 2017-03-03 11:37:11
As you can notice from the tables, sales table id increasing with the addition of 2 and it happened to sale_details table as well.
My questions are as following: -
1) I'm kinda new to cakephp 3, so is this the right method to save data into multiple tables? I removed the following lines and I'm still able to save data into those tables. What to do with 'associated' here?
SalesController.php
if ($this->request->is('ajax')) {
$sales = $this->Sales->newEntity(
$this->request->data(),
[
'validate' => 'create',
/*'associated' => [
'SaleDetails' => ['validate' => 'create']
]*/ // removed
]
);
if ($this->Sales->save($sales)) {
//code
}
}
2) I can't figure out why those id increasing with the addition of 2. I'm pretty sure I've set auto_increment = 1 for both table.
System variable auto_increment_increment has been set to 2. Not sure how could this happen though.
Thanks in advance.
Yes, that is the correct way to save associations.
Your associations are still being converted (and consequently saved) even without specifying them via the associated option, because first level associations are allowed by default, ie when removing the option, all first level associations can be converted, and when specifying it as shown in your example, only SaleDetails associations can be converted.
Quotes from the docs:
By default all the associations on this table will be hydrated. You can limit which associations are built, or include deeper associations using the options parameter
API > \Cake\ORM\Table::newEntity()
When you are saving an entity, you can also elect to save some or all of the associated entities. By default all first level entities will be saved.
Cookbook > Datbase Access & ORM > Saving Data > Saving Associations
See also
Cookbook > Datbase Access & ORM > Saving Data > Converting Request Data into Entities
I am novice to SQL and
I have two tables Ticket and TicketAttributes with following Schema
CREATE TABLE [dbo].[Ticket](
[TicketID] [int] IDENTITY(1,1) NOT NULL, --Primary key
[Category] [varchar](256) NOT NULL,
[Description] [varchar](256) NULL,
[LibID] [int] NOT NULL,
[Status] [smallint] NULL,
[LogID] [int] NULL)
Ticket Attributes
CREATE TABLE [dbo].[TicketAttributes](
[TicketID] [int] NOT NULL,
[TicketAttrID] [int] IDENTITY(1,1) NOT NULL,
[AttributeID] [int] NOT NULL,
[AttributeGroup] [varchar](255) NULL,
[AttributeValue] [nvarchar](max) NULL,
[Status] [smallint] NULL,
[LogID] [int] NULL)
Where Ticket Attribute is another table that stores different attributes of a ticket like TicketStatus, TicketCategory etc..
Now I need to generate a report that looks like
TicketStatus1 TicketStatus 2 TicketStatus3
-----------------------------------------------------------------
TicketCategory1 7 3
Ticketcategory2 4
TicketCategory3 8
I want to see the count of each of the status of each ticket category.
For Eg:-
I have the following Data in TicketTable
----------------------------------------------
TicketID Name Price Date
------------------------------------------------
155 Ticket4 $20 16 Jan 2016
157 Ticket3 $300 17 Jan 2016
158 Ticket1 $100 18 Jan 2016
159 Ticket2 $500 19 Jan 2016
Now in the TicketAttribute Table
----------------------------------------------
TicketID AttributeID AttributeValue
------------------------------------------------
155 500 Joe
155 600 Reserved
155 700 Economy
155 800 San Jose
where AttributeIDs
500=Nameofthe Passenger
600= Status of Ticket
700= Class
800= Destination
Now lets say I want to see what is the count of number of active tickets in each of the class per status
Booked Cancelled PaymentPending ............
-----------------------------------------------------------------
Economy 7 3
Economy Plus 4
Business 8
Hope I am clear now.
how to go about this using SQL Query
USING PIVOT
;WITH cte AS (
SELECT
c.AttributeValue as Class
,s.AttributeValue as StatusOfTicket
FROM
Ticket t
LEFT JOIN TicketAttributes c
ON t.TicketId = c.TicketId
AND c.AttributeID = 700
LEFT JOIN TicketAttributes s
ON t.TicketId = s.TicketId
AND s.AttributeID = 600
)
SELECT *
FROM
cte
PIVOT (
COUNT(StatusOfTicket) FOR StatusOfTicket IN (Reserved,Cancelled,PaymentPending)
) p
USING Conditional Aggregation:
SELECT
c.AttributeValue as Class
,COUNT(DISTINCT CASE WHEN s.AttributeValue = 'Reserved' THEN c.TicketId END) as Reserved
,COUNT(DISTINCT CASE WHEN s.AttributeValue = 'Cancelled' THEN c.TicketId END) as Cancelled
,COUNT(DISTINCT CASE WHEN s.AttributeValue = 'PaymentPending' THEN c.TicketId END) as PaymentPending
FROM
Ticket t
LEFT JOIN TicketAttributes c
ON t.TicketId = c.TicketId
AND c.AttributeID = 700
LEFT JOIN TicketAttributes s
ON t.TicketId = s.TicketId
AND s.AttributeID = 600
GROUP BY
c.AttributeValue